package com.sinog.biz.service.business.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sinog.biz.config.ProvinceCodes3Config;
import com.sinog.biz.mapper.havexml.AbLieguanMapper;
import com.sinog.biz.mapper.havexml.AbPrisonerMapper;
import com.sinog.biz.mapper.havexml.AreaCodeFullMapper;
import com.sinog.biz.mapper.havexml.ChangeTableMapper;
import com.sinog.biz.mapper.havexml.DepartmentMapper;
import com.sinog.biz.mapper.havexml.HnInterfaceOppositeMapper;
import com.sinog.biz.mapper.havexml.PrisaveTempMapper;
import com.sinog.biz.mapper.havexml.PrisonerFxExcelTempMapper;
import com.sinog.biz.mapper.havexml.PrisonerFxMapper;
import com.sinog.biz.mapper.havexml.PrisonerMainExcelTempMapper;
import com.sinog.biz.mapper.havexml.PrisonerMainMapper;
import com.sinog.biz.mapper.havexml.PrisonerSrExcelTempMapper;
import com.sinog.biz.mapper.havexml.PrisonerXjxxMapper;
import com.sinog.biz.mapper.havexml.PrisonerZnExcelTempMapper;
import com.sinog.biz.mapper.havexml.SystemCodeMapper;
import com.sinog.biz.mapper.havexml.UploadAppendixFileMapper;
import com.sinog.biz.mapper.havexml.VerificationMapper;
import com.sinog.biz.mapper.havexml.XjReceiptDataVoMapper;
import com.sinog.biz.mapper.havexml.XjReceiptMapper;
import com.sinog.biz.mapper.havexml.XtjcKsywxtMapper;
import com.sinog.biz.mapper.havexml.other.LiuChengOldDataMapper;
import com.sinog.biz.service.api.XmlMinitoringService;
import com.sinog.biz.service.business.PrisonerMainService;
import com.sinog.biz.service.serviceimpl.AbPrisonersService;
import com.sinog.biz.service.serviceimpl.AbXiaozuService;
import com.sinog.biz.service.serviceimpl.PrisonerMainTowService;
import com.sinog.biz.service.xml.InterfaceDockingService;
import com.sinog.biz.util.BusinessUtils;
import com.sinog.biz.util.CheckFieldValue;
import com.sinog.biz.util.CodeUrlUtils;
import com.sinog.biz.util.ConditionUtils;
import com.sinog.biz.util.IdGen;
import com.sinog.biz.util.JdbcUtils;
import com.sinog.biz.util.smlib.Sm4;
import com.sinog.core.domain.AbLieguan;
import com.sinog.core.domain.AbPrisonersResultVo;
import com.sinog.core.domain.AbXiaozuResultVo;
import com.sinog.core.domain.ChangeTable;
import com.sinog.core.domain.Department;
import com.sinog.core.domain.InterProvincialBusiness;
import com.sinog.core.domain.PrisaveTemp;
import com.sinog.core.domain.PrisonerCjpg;
import com.sinog.core.domain.PrisonerFx;
import com.sinog.core.domain.PrisonerHc;
import com.sinog.core.domain.PrisonerMain;
import com.sinog.core.domain.PrisonerMainExcelTemp;
import com.sinog.core.domain.PrisonerXjxx;
import com.sinog.core.domain.SystemCode;
import com.sinog.core.domain.XjReceipt;
import com.sinog.core.domain.XjReceiptData;
import com.sinog.core.domain.xml.HnInterfaceOpposite;
import com.sinog.core.model.LiuChengHcAndMainVo;
import com.sinog.core.model.PrisonerMainAndHcVo;
import com.sinog.core.model.PrisonerXixxVo;
import com.sinog.core.model.PrisonerXjxxInVo;
import com.sinog.core.model.UserDTO;
import com.sinog.core.model.XjReceiptDataVo;
import com.sinog.core.model.xml.HnMessageVo;
import com.sinog.core.util.AssemblyConversionUtils;
import com.sinog.core.util.DateUtil;
import com.sinog.core.util.JsonUtil;
import com.sinog.core.util.MapUtil;
import com.sinog.core.util.PageReturnUtil;
import com.sinog.core.util.PhoneUtil;
import com.sinog.core.util.StrUtil;
import com.sinog.core.utilbean.Constants;
import com.sinog.core.utilbean.Result;
import com.sinog.core.utilbean.ReturnCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * @author -
 * @desc 预安置管理 - 服刑人员信息录入
 * @date 2020-01-19-14:02
 */
@Service
@Slf4j
public class PrisonerMainServiceImpl extends ServiceImpl<PrisonerMainMapper,PrisonerMain> implements PrisonerMainService {

    @Resource
    private SystemCodeMapper systemCodeMapper;
    @Resource
    private PrisonerMainMapper prisonerMainMapper;
    @Resource
    private PrisonerMainExcelTempMapper prisonerMainExcelTempMapper;
    @Resource
    private XjReceiptMapper xjReceiptMapper;
    @Resource
    private PrisonerXjxxServiceImpl prisonerXjxxService;
    @Resource
    private AbPrisonersService abPrisonersService;
    @Resource
    private AbXiaozuService abXiaozuService;
    @Resource
    private PrisonerMainTowService prisonerMainTowService;
    @Resource
    private PrisaveTempMapper prisaveTempMapper;
    @Resource
    private VerificationMapper verificationMapper;
    @Resource
    private UploadAppendixFileMapper uploadAppendixFileMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private PrisonerFxMapper prisonerFxMapper;
    @Autowired
    private XjReceiptDataVoMapper xjReceiptDataVoMapper;
    @Resource
    private AbPrisonerMapper abPrisonerMapper;
    @Resource
    private XtjcKsywxtMapper businessMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    @Qualifier("middleJdbcTemplate")
    private JdbcTemplate middleJdbcTemplate;
    @Autowired
    private XmlMinitoringService xmlMinitoringService;
    @Autowired
    private HnInterfaceOppositeMapper hnInterfaceOppositeMapper;
    @Autowired
    private AbLieguanMapper abLieguanMapper;
    @Autowired
    private PrisonerSrExcelTempMapper prisonerSrExcelTempMapper;
    @Autowired
    private PrisonerZnExcelTempMapper prisonerZnExcelTempMapper;
    @Autowired
    private PrisonerFxExcelTempMapper prisonerFxExcelTempMapper;
    @Autowired
    private PrisonerXjxxMapper prisonerXjxxMapper;
    @Autowired
    private LiuChengOldDataMapper liuChengOldDataMapper;
    @Autowired
    private InterfaceDockingService interfaceDockingService;
    @Resource
    private AreaCodeFullMapper areaCodeFullMapper;
    @Resource
    private ProvinceCodes3Config provinceCodes3Config;
    @Resource
    private ChangeTableMapper changeTableMapper;
    @Resource
    private DepartmentMapper departmentMapper;

    /**
     * 预安置管理 - 预安置人员信息录入 - 查询列表
     * listType 列表类型 100:默认列表    101:户籍完整人员  102:查不清户籍   103:有未成年子女  104:无照片或指纹人员  105:姓名重复人员
     * @param pageIndex 起始索引
     * @param pageSize 数据条数
     * @param querykey 查询条件
     * @return String 预安置人员信息录入数据列表
     */
    @Override
    public String getInmatesList(Integer pageIndex,Integer pageSize,String querykey) {
        Map<String,Object> mapTem = MapUtil.requestConversionToMap(JsonUtil.toMap(querykey));
        assert !mapTem.isEmpty();
        Page<Map<String,String>> page = new Page<>(pageIndex + 1,pageSize);
        if(Constants.NumberStr.NUM_STR_ONE_ZERO_FIVE.equals(mapTem.get("listType"))) {
            //查询姓名重复列表
            page = page.setRecords(prisonerMainMapper.nameRepetitionInfo(page,mapTem));
        } else {
            //默认查询、其他快捷查询
            page = page.setRecords(prisonerMainMapper.getInmatesList(page,mapTem));
        }
        return PageReturnUtil.pageReturn(page);
    }

    /**
     * 预安置管理 - 预安置人员信息录入 - 批量导入 查询列表
     * @param pageIndex 起始页
     * @param pageSize 止页
     * @param querykey 搜索条件
     * @return String
     */
    @Override
    public String getInmatesListExcel(Integer pageIndex,Integer pageSize,String querykey) {
        Map<String,Object> mapTem = MapUtil.requestConversionToMap(JsonUtil.toMap(querykey));
        if(mapTem.isEmpty()) {
            return null;
        }
        Page<Map<String,String>> page = new Page<>(pageIndex + 1,pageSize);
        page = page.setRecords(prisonerMainExcelTempMapper.getInmatesList(page,mapTem));
        return PageReturnUtil.pageReturn(page);
    }

    /**
     * 预安置管理 - 预安置人员信息录入 - 基本信息(新增)
     * @param data 基本信息
     * @param user 当前登录用户
     * @param flag 新增修改标志 0:新增,1:修改
     * @return Result
     * 罪犯编号规则：  当前用的departid(5位)+部门等级（2位）+当前年份（2位）+递增数字（7位）
     * 例：监狱     12010   01   20   0000001
     * 看守所   12150   02   20   0000002
     * 社矫中心 12250   05   20   0000003
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result saveBaseInfo(String data,UserDTO user,String flag) {
        return save(data,user,flag);
    }

    /**
     * 预安置管理 - 预安置人员信息录入 - 基本信息(新增)
     * @param data 罪犯基本信息
     * @param user 用户信息
     * @param flag 新增修改标志 0:新增,1:修改,2:补录新增,3:补录修改
     * @return Result
     */
    @Transactional(rollbackFor = Exception.class)
    public Result save(String data,UserDTO user,String flag) {
        //1、解析参数
        PrisonerMain prisonerMain = JsonUtil.toBean(data,PrisonerMain.class);
        Map<String,Object> paramMap = JsonUtil.toMap(data);
        Map<String,String> paramMap1 = new HashMap<>(16);
        Date date = new Date();
        //2、校验身份证是否存在,如果不为‘无’则校验重复
        String idNum = prisonerMain.getIdNum();
        String pName = prisonerMain.getPName();
        PrisonerMain oldPrisonerMain = null;
        boolean insertFlag = (Constants.NumberStr.NUM_STR_ZERO.equals(flag) || Constants.NumberStr.NUM_STR_TWO.equals(flag)) && StringUtils.isNotBlank(idNum) && !Constants.StrFinalValue.WU.equals(idNum);
        //这里只判断是否属于修改，是否为无到修改逻辑内判断
        boolean updateFlag = Constants.NumberStr.NUM_STR_ONE.equals(flag) || Constants.NumberStr.NUM_STR_THREE.equals(flag);
        // 新增逻辑判断身份证是否存在
        if(insertFlag) {
            //如果根据姓名和身份证查询数据库中是否存在该数据
            String result = checkIdNumRepeat(idNum,pName);
            if(Constants.NumberStr.NUM_STR_ZERO.equals(result)) {
                return Result.failure(ReturnCode.FUXING_EXISTS);
            } else if(Constants.NumberStr.NUM_STR_ONE.equals(result)) {
                return Result.failure(ReturnCode.BASEINFO_EXISTS);
            }
            // 修改逻辑判断身份证是否存在
        } else if(updateFlag) {
            oldPrisonerMain = prisonerMainMapper.selectPrisonerMain(prisonerMain.getPriNum());
            String idNum1 = oldPrisonerMain.getIdNum();
            if(idNum1 == null || Constants.StrFinalValue.WU.equals(idNum)) {
                idNum1 = Constants.IdNUMEncode.ID_NUM_ENCODE_WU;
            }
            if(!idNum.equals(Sm4.decryptEcb(idNum1))) {
                String result = checkIdNumRepeat(idNum,pName);
                if(Constants.NumberStr.NUM_STR_ZERO.equals(result)) {
                    return Result.failure(ReturnCode.FUXING_EXISTS);
                } else if(Constants.NumberStr.NUM_STR_ONE.equals(result)) {
                    return Result.failure(ReturnCode.BASEINFO_EXISTS);
                }
            }
        }
        //3、设置创建用户时间等、服刑单位、监所及上级单位
        if ((Constants.NumberStr.NUM_STR_ZERO.equals(flag) || Constants.NumberStr.NUM_STR_TWO.equals(flag))){
            prisonerMain.setCreateUser(user.getAccount());
            prisonerMain.setCreateTime(date);
        }
        prisonerMain.setUpdateUser(user.getAccount());
        prisonerMain.setUpdateTime(date);
        //衔接途径
        String tujing = (String)paramMap.get("tujing");
        if(null != tujing) {
            //02代表解教、01代表监狱
            if(Constants.NumberStr.NUM_STR_ZERO_TWO.equals(tujing)) {
                // 服刑单位id -> 服刑单位
                prisonerMain.setPdanwei(user.getDepartid());
                // 服刑单位名称 -> 部门名称
                prisonerMain.setPdanweiName(user.getDepartName());
                // 所在监所 -> 当前登录用户level,监狱-> 01,看守所-> 02,社矫中心->05
                prisonerMain.setPtype(Constants.NumberStr.NUM_STR_ZERO_FIVE);
                // 所在监所上级监狱局
                prisonerMain.setPrisonFather(user.getOrgid());
                // 录入来源 1
                prisonerMain.setPstate(Constants.InputEspecially.INPUT_SFSJJ);
            } else if(Constants.NumberStr.NUM_STR_ZERO_ONE.equals(tujing)) {
                String pdanwei = null == paramMap.get("addPrison") ? "" : paramMap.get("addPrison").toString();
                Department department = departmentMapper.getDepartmentById(pdanwei);
                // 服刑单位
                // 服刑单位id
                prisonerMain.setPdanwei(pdanwei);
                // 服刑单位名称
                prisonerMain.setPdanweiName(department.getName());
                // 所在监所
                prisonerMain.setPtype(Constants.NumberStr.NUM_STR_ZERO_ONE);
                // 所在监所上级监狱局
                prisonerMain.setPrisonFather(department.getPid());
                //所在监所上级监狱局名称
                // 录入来源 2
                prisonerMain.setPstate(Constants.InputEspecially.INPUT_SFSJY_INTERFACE);
            }
            // 普通录入逻辑
        } else {
            // 服刑单位id
            prisonerMain.setPdanwei(user.getDepartid());
            // 服刑单位名称
            prisonerMain.setPdanweiName(user.getDepartName());
            //监所类型
            prisonerMain.setPtype(user.getLevel());
            // 所在监所上级监狱局
            prisonerMain.setPrisonFather(user.getOrgid());
        }
        //4、设置户籍信息
        String nativeproNameCodeId = "";
        String nativecityNameCodeId = "";
        String nativecouNameCodeId = "";
        String nativevillNameCodeId = "";
        String nativenum = "";
        // 判断户籍类型 :01:农村户籍 02:城镇户籍 04:非大陆籍
        String priAddr = prisonerMain.getPriAddr();
        //户籍大类（01：户籍完整人员 02：查不清户籍人员）
        String hjType = prisonerMain.getHjType();
        //4.1、查不清户籍
        if(Constants.NumberStr.NUM_STR_ZERO_TWO.equals(hjType)) {
            String investigateProCodeId = prisonerMain.getInvestigatePro();
            String investigateCityCodeId = prisonerMain.getInvestigateCity();
            String investigateCouCodeId = prisonerMain.getInvestigateCou();
            String investigateVillCodeId = prisonerMain.getInvestigateVill();
            //设置原侦查机关名称
            if(StringUtils.isNotBlank(investigateProCodeId)) {
                Map<String,String> areaNames = areaCodeFullMapper.getAreaNames(investigateProCodeId,investigateCityCodeId,investigateCouCodeId,investigateVillCodeId);
                if(areaNames == null) {
                    return Result.failure(ReturnCode.SAVE_FAILED);
                }
                prisonerMain.setInvestigateProName(areaNames.get("shengName"));
                prisonerMain.setInvestigateCityName(areaNames.get("dishiName"));
                prisonerMain.setInvestigateCouName(areaNames.get("quxianName"));
                prisonerMain.setInvestigateVillName(areaNames.get("jiedaoName"));
                if(StringUtils.isBlank(investigateCityCodeId)) {
                    prisonerMain.setInvestigateCityName("");
                }
                if(StringUtils.isBlank(investigateCouCodeId)) {
                    prisonerMain.setInvestigateCouName("");
                }
                if(StringUtils.isBlank(investigateVillCodeId)) {
                    prisonerMain.setInvestigateVillName("");
                }
            } else {
                prisonerMain.setInvestigateProName("");
                prisonerMain.setInvestigateCityName("");
                prisonerMain.setInvestigateCouName("");
                prisonerMain.setInvestigateVillName("");
            }
            //原侦查机关地址ID赋值给户籍地址ID
            nativeproNameCodeId = investigateProCodeId;
            nativecityNameCodeId = investigateCityCodeId;
            nativecouNameCodeId = investigateCouCodeId;
            nativevillNameCodeId = investigateVillCodeId;
            nativenum = prisonerMain.getInvestigateNum();
        } else if(Constants.NumberStr.NUM_STR_ZERO_ONE.equals(priAddr) || Constants.NumberStr.NUM_STR_ZERO_TWO.equals(priAddr)) {
            //4.2、农村城镇
            nativeproNameCodeId = prisonerMain.getNativepro();
            nativecityNameCodeId = prisonerMain.getNativecity();
            nativecouNameCodeId = prisonerMain.getNativecou();
            nativevillNameCodeId = prisonerMain.getNativevill();
            nativenum = prisonerMain.getNativenum();
            //设置农村城镇居住地名称
            String placeproNameCodeId = prisonerMain.getPlacepro();
            String placecityNameCodeId = prisonerMain.getPlacecity();
            String placecouNameCodeId = prisonerMain.getPlacecou();
            String placevillNameCodeId = prisonerMain.getPlacevill();
            if(StringUtils.isNotBlank(placeproNameCodeId)) {
                Map<String,String> areaNames = areaCodeFullMapper.getAreaNames(placeproNameCodeId,placecityNameCodeId,placecouNameCodeId,placevillNameCodeId);
                if(areaNames == null) {
                    return Result.failure(ReturnCode.SAVE_FAILED);
                }
                prisonerMain.setPlaceproName(areaNames.get("shengName"));
                prisonerMain.setPlacecityName(areaNames.get("dishiName"));
                prisonerMain.setPlacecouName(areaNames.get("quxianName"));
                prisonerMain.setPlacevillName(areaNames.get("jiedaoName"));
                if(StringUtils.isBlank(placecityNameCodeId)) {
                    prisonerMain.setPlacecityName("");
                }
                if(StringUtils.isBlank(placecouNameCodeId)) {
                    prisonerMain.setPlacecouName("");
                }
                if(StringUtils.isBlank(placevillNameCodeId)) {
                    prisonerMain.setPlacevillName("");
                }
            } else {
                prisonerMain.setPlaceproName("");
                prisonerMain.setPlacecityName("");
                prisonerMain.setPlacecouName("");
                prisonerMain.setPlacevillName("");
            }
        } else if(Constants.NumberStr.NUM_STR_ZERO_FOUR.equals(priAddr)) {
            //非大陆
            String arrestproNameCodeId = prisonerMain.getArrestpro();
            String arrestcityNameCodeId = prisonerMain.getArrestcity();
            String arrestcouNameCodeId = prisonerMain.getArrestcou();
            String arrestvillNameCodeId = prisonerMain.getArrestvill();
            //设置逮捕机关名称
            if(StringUtils.isNotBlank(arrestproNameCodeId)) {
                Map<String,String> areaNames = areaCodeFullMapper.getAreaNames(arrestproNameCodeId,arrestcityNameCodeId,arrestcouNameCodeId,arrestvillNameCodeId);
                if(areaNames == null) {
                    return Result.failure(ReturnCode.SAVE_FAILED);
                }
                prisonerMain.setArrestproName(areaNames.get("shengName"));
                prisonerMain.setArrestcityName(areaNames.get("dishiName"));
                prisonerMain.setArrestcouName(areaNames.get("quxianName"));
                prisonerMain.setArrestvillName(areaNames.get("jiedaoName"));
                if(StringUtils.isBlank(arrestcityNameCodeId)) {
                    prisonerMain.setArrestcityName("");
                }
                if(StringUtils.isBlank(arrestcouNameCodeId)) {
                    prisonerMain.setArrestcouName("");
                }
                if(StringUtils.isBlank(arrestvillNameCodeId)) {
                    prisonerMain.setArrestvillName("");
                }
            } else {
                prisonerMain.setArrestproName("");
                prisonerMain.setArrestcityName("");
                prisonerMain.setArrestcouName("");
                prisonerMain.setArrestvillName("");
            }
            //非大陆逮捕机关地址ID赋值给户籍地址ID
            nativeproNameCodeId = arrestproNameCodeId;
            nativecityNameCodeId = arrestcityNameCodeId;
            nativecouNameCodeId = arrestcouNameCodeId;
            nativevillNameCodeId = arrestvillNameCodeId;
            nativenum = prisonerMain.getArrestnum();
        }
        //4.3、设置户籍地址code
        prisonerMain.setNativepro(nativeproNameCodeId);
        prisonerMain.setNativecity(nativecityNameCodeId);
        prisonerMain.setNativecou(nativecouNameCodeId);
        prisonerMain.setNativevill(nativevillNameCodeId);
        //4.4设置户籍地址名
        if(StringUtils.isNotBlank(nativeproNameCodeId)) {
            Map<String,String> areaNames = areaCodeFullMapper.getAreaNames(nativeproNameCodeId,nativecityNameCodeId,nativecouNameCodeId,nativevillNameCodeId);
            if(areaNames == null) {
                return Result.failure(ReturnCode.SAVE_FAILED);
            }
            prisonerMain.setNativeproName(areaNames.get("shengName"));
            prisonerMain.setNativecityName(areaNames.get("dishiName"));
            prisonerMain.setNativecouName(areaNames.get("quxianName"));
            prisonerMain.setNativevillName(areaNames.get("jiedaoName"));
            if(StringUtils.isBlank(nativecityNameCodeId)) {
                prisonerMain.setNativecityName("");
            }
            if(StringUtils.isBlank(nativecouNameCodeId)) {
                prisonerMain.setNativecouName("");
            }
            if(StringUtils.isBlank(nativevillNameCodeId)) {
                prisonerMain.setNativevillName("");
            }
        } else {
            prisonerMain.setNativeproName("");
            prisonerMain.setNativecityName("");
            prisonerMain.setNativecouName("");
            prisonerMain.setNativevillName("");
        }
        prisonerMain.setNativenum(nativenum);
        //5、当前台没有传递过来罪犯ID（第一次新增的时候）,生成犯罪编号
        if(StringUtils.isBlank(prisonerMain.getPriNum())) {
            //生成犯罪编号
            String priNum = BusinessUtils.makePriNum(prisonerMainMapper,stringRedisTemplate,user.getDepartid(),user.getLevel());
            if(Constants.StrFinalValue.ERROR.equals(priNum)) {
                return Result.failure(ReturnCode.FAILURE);
            }
            prisonerMain.setPriNum(priNum);
        }
        //6、设置其他信息
        //去掉输入信息的 多余的空格
        prisonerMain.setPName(prisonerMain.getPName().trim());
        prisonerMain.setUsedName(prisonerMain.getUsedName().trim());
        prisonerMain.setAdduserid(user.getDepartid());
        prisonerMain.setAddusername(user.getUsername());
        prisonerMain.setDelFlag(Constants.NumberStr.NUM_STR_ZERO);
        String strid = IdGen.strid();
        prisonerMain.setId(strid);
        //设置人员来源
        if(Constants.NumberStr.NUM_STR_ZERO.equals(flag) || Constants.NumberStr.NUM_STR_TWO.equals(flag)) {
            setPrisonerPstate(user,prisonerMain);
        }
        if(Constants.NumberStr.NUM_STR_TWO.equals(flag) || Constants.NumberStr.NUM_STR_THREE.equals(flag)) {
            prisonerMain.setState(Constants.NumberStr.NUM_STR_THREE);
            prisonerMain.setStateXj(Constants.NumberStr.NUM_STR_ONE);
        }
        //7、插入主表
        boolean insert;
        if(idNum.length() > 18) {
            insert = prisonerMain.setIdNum(idNum).insertOrUpdate();
        } else {
            insert = prisonerMain.setIdNum(Sm4.encryptEcb(idNum)).insertOrUpdate();
        }
        //8、返回数据
        Map<String,String> mapTem = new HashMap<>(16);
        mapTem.put("id",prisonerMain.getId());
        mapTem.put("priNum",prisonerMain.getPriNum());
        //9、服刑人员所在监所
        boolean flag1 = saveFlag(prisonerMain,Constants.Number.NUM_ONE,user);
        if(flag1 && insert) {
            // 修改逻辑处理
            if(Constants.NumberStr.NUM_STR_ONE.equals(flag)) {
                //失败列表中编辑主信息需要同时更新hc表信息
                String priNum = prisonerMain.getPriNum();
                PrisonerHc prisonerHc = new PrisonerHc();
                //服刑人员信息核查对象
                prisonerHc.setPriNum(priNum);
                prisonerHc = prisonerMainMapper.prisonerHcByPriNum(priNum);
                prisonerHc.setUpdateTime(date);
                prisonerHc.setUpdateUser(user.getAccount());
                prisonerHc.setSignFlag(Constants.NumberStr.NUM_STR_ZERO);
                // 核查失败编辑按钮特殊处理 hjtype = 02(查不清户籍) hjtype = 04(非大陆户籍)
                if(Constants.NumberStr.NUM_STR_FOUR.equals(oldPrisonerMain.getState()) && Constants.NumberStr.NUM_STR_ZERO_TWO.equals(hjType)) {
                    prisonerHc.setPushState(Constants.NumberStr.NUM_STR_FOUR);
                    prisonerHc.setFailurenum(Constants.NumberStr.NUM_STR_TWO);
                    prisonerHc.setSpecialFlag(Constants.NumberStr.NUM_STR_ONE);
                } else if(Constants.NumberStr.NUM_STR_FOUR.equals(oldPrisonerMain.getState()) && Constants.NumberStr.NUM_STR_ZERO_FOUR.equals(priAddr)) {
                    prisonerHc.setPushState(Constants.NumberStr.NUM_STR_ZERO);
                    prisonerHc.setFailurenum(Constants.NumberStr.NUM_STR_ZERO);
                    prisonerHc.setSpecialFlag(Constants.NumberStr.NUM_STR_ZERO);
                }
                paramMap1.put("priNum",priNum);
                paramMap1.put("signFlag",Constants.NumberStr.NUM_STR_ZERO);
                verificationMapper.updatePrisonerHcByParam(prisonerHc,paramMap1);
                //查询ab_prisoner是否有数据，用于安置帮教-全部人员内的编辑功能
                Map<String,Object> baseInfoByPriNum = abPrisonerMapper.getBaseInfoByPriNum(priNum);
                if(null != baseInfoByPriNum && !baseInfoByPriNum.isEmpty()) {
                    abPrisonerMapper.updateDataFromMain(priNum);
                }
                // 山西个性化需求:司法所编辑服刑信息，保存中间表
                String localCode = CodeUrlUtils.getLocalCode();
                if(Constants.XzqhCode.SHAN1XI.equals(localCode) && StringUtils.equals(user.getLevel(),Constants.OrgLevel.LEVEL_SFS)) {
                    changePrisonerMain(prisonerMain,user);
                }
                // 补录新增逻辑
            } else if(Constants.NumberStr.NUM_STR_TWO.equals(flag)) {
                //对安帮表添加数据
                AbPrisonersResultVo abPrisonersResultVo = saveblAbprisoners(prisonerMain);
                abPrisonerMapper.insert(abPrisonersResultVo);
                // 保存衔接信息
                saveblPrisonerXjxx(prisonerMain,paramMap);
                //abPrisonersResultVo
                //对小组表进行操作
                AbXiaozuResultVo abXiaozuResultVo = saveXiaozu(prisonerMain);
                abXiaozuResultVo.setParentId(abPrisonersResultVo.getId());
                abXiaozuService.save(abXiaozuResultVo);
            } else if(Constants.NumberStr.NUM_STR_THREE.equals(flag)) {
                // 修改abPrisoners信息
                AbPrisonersResultVo abPrisonersResultVo = abPrisonerMapper.selectOne(new QueryWrapper<AbPrisonersResultVo>().eq("pri_num",prisonerMain.getPriNum())
                                                                                                                            .last("limit 1"));
                if(null != abPrisonersResultVo) {
                    AbPrisonersResultVo abPrisonersResultVo1 = saveblAbprisoners(prisonerMain);
                    abPrisonersResultVo1.setId(prisonerMain.getId());
                    abPrisonerMapper.updateById(abPrisonersResultVo1);
                    //如果更新人员信息，小组信息也需要修改
                    AbXiaozuResultVo xiaozuResultVo = abXiaozuService.getOne(new QueryWrapper<AbXiaozuResultVo>().eq("pri_num",prisonerMain.getPriNum())
                                                                                                                 .last(" limit 1"));
                    xiaozuResultVo.setPriNum(prisonerMain.getPriNum());
                    xiaozuResultVo.setXname(prisonerMain.getPName());
                    xiaozuResultVo.setXsex(prisonerMain.getSex());
                    xiaozuResultVo.setUpdateTime(prisonerMain.getUpdateTime());
                    xiaozuResultVo.setUpdateUser(prisonerMain.getUpdateUser());
                    xiaozuResultVo.updateById();
                }
            }
            //*****************************************************************************************
            return Result.success(mapTem);
        }
        return Result.failure(ReturnCode.SAVE_FAILED);
    }

    /**
     * 服刑人员数据来源
     * @param user 当前登录用户
     * @param prisonerMain prisonerMain
     */
    public void setPrisonerPstate(UserDTO user,PrisonerMain prisonerMain) {
        if(Constants.OrgLevel.LEVEL_KSS.equals(user.getLevel())) {
            //看守所录入
            prisonerMain.setPstate(Constants.InputEspecially.INPUT_KSS);
        }
        if(Constants.OrgLevel.LEVEL_JY.equals(user.getLevel())) {
            //监狱录入
            prisonerMain.setPstate(Constants.InputEspecially.INPUT_JY);
        }
        if(Constants.OrgLevel.LEVEL_SJZX.equals(user.getLevel())) {
            //社娇录入
            prisonerMain.setPstate(Constants.InputEspecially.INPUT_SJ);
        }
    }

    /**
     * 预安置管理 - 预安置人员信息录入 - 批量导入 - 基本信息(更新)
     * @param data 业务数据
     * @param user 当前登录用户
     * @return Result
     */
    @Override
    public Result updataBaseInfoExcel(String data,UserDTO user) {
        //1、解析参数
        PrisonerMainExcelTemp prisonerMain = JsonUtil.toBean(data,PrisonerMainExcelTemp.class);
        prisonerMain.setIdNum(Sm4.encryptEcb(prisonerMain.getIdNum()));
        Date date1 = new Date();
        prisonerMain.setUpdateUser(user.getAccount());
        prisonerMain.setUpdateTime(date1);
        Map<String,Object> paramMap = JsonUtil.toMap(data);
        prisonerMain.setCheckFlag(Constants.NumberStr.NUM_STR_ZERO);
        //mainCount>0说明数据未填写完整
        //mainCount=0说明数据已经完整
        //当下面四个值都为0就设置主表的success_flag=0；
        int fxCount = prisonerFxExcelTempMapper.selectFxByCheckFlag(prisonerMain.getPriNum());
        int srCount = prisonerSrExcelTempMapper.selectSrByCheckFlag(prisonerMain.getPriNum());
        int znCount = prisonerZnExcelTempMapper.selectZnByCheckFlag(prisonerMain.getPriNum());
        if(fxCount + srCount + znCount == 0) {
            prisonerMain.setSuccessFlag(Constants.NumberStr.NUM_STR_ZERO);
        }
        //Todo 少东西
        //3、设置户籍信息
        String nativeproNameCodeId = "";
        String nativecityNameCodeId = "";
        String nativecouNameCodeId = "";
        String nativevillNameCodeId = "";
        String nativenum = "";
        // 判断户籍类型
        String priAddrs = paramMap.get("priAddr").toString();
        //户籍大类（01：户籍完整人员 02：查不清户籍人员）
        String hjType = paramMap.get("hjType").toString();
        // 户籍为完整人员 农村/城镇户籍
        Map<String,String> areaNames;
        if(!Constants.NumberStr.NUM_STR_ZERO_TWO.equals(hjType)) {
            if(Constants.NumberStr.NUM_STR_ZERO_ONE.equals(priAddrs) || Constants.NumberStr.NUM_STR_ZERO_TWO.equals(priAddrs)) {
                nativeproNameCodeId = paramMap.get("nativepro").toString();
                nativecityNameCodeId = paramMap.get("nativecity").toString();
                nativecouNameCodeId = paramMap.get("nativecou").toString();
                nativevillNameCodeId = paramMap.get("nativevill").toString();
                nativenum = paramMap.get("nativenum").toString();
                // 居住地所在省、市、县、街道名称
                String placeproNameCodeId = paramMap.get("placepro").toString();
                String placecityNameCodeId = paramMap.get("placecity").toString();
                String placecouNameCodeId = paramMap.get("placecou").toString();
                String placevillNameCodeId = paramMap.get("placevill").toString();
                String placenum = paramMap.get("placenum").toString();
                prisonerMain.setPlacepro(placeproNameCodeId);
                prisonerMain.setPlacecity(placecityNameCodeId);
                prisonerMain.setPlacecou(placecouNameCodeId);
                prisonerMain.setPlacevill(placevillNameCodeId);
                if(StringUtils.isNotBlank(placeproNameCodeId)) {
                    areaNames = areaCodeFullMapper.getAreaNames(placeproNameCodeId,placecityNameCodeId,placecouNameCodeId,placevillNameCodeId);
                    if(areaNames == null) {
                        return Result.failure(ReturnCode.SAVE_FAILED);
                    }
                    prisonerMain.setPlaceproName(areaNames.get("shengName"));
                    prisonerMain.setPlacecityName(areaNames.get("dishiName"));
                    prisonerMain.setPlacecouName(areaNames.get("quxianName"));
                    prisonerMain.setPlacevillName(areaNames.get("jiedaoName"));
                    if(StringUtils.isBlank(placecityNameCodeId)) {
                        prisonerMain.setPlacecityName("");
                    }
                    if(StringUtils.isBlank(placecouNameCodeId)) {
                        prisonerMain.setPlacecouName("");
                    }
                    if(StringUtils.isBlank(placevillNameCodeId)) {
                        prisonerMain.setPlacevillName("");
                    }
                } else {
                    prisonerMain.setPlaceproName("");
                    prisonerMain.setPlacecityName("");
                    prisonerMain.setPlacecouName("");
                    prisonerMain.setPlacevillName("");
                }
                prisonerMain.setPlacenum(placenum);
            }
        }
        prisonerMain.setNativepro(nativeproNameCodeId);
        prisonerMain.setNativecity(nativecityNameCodeId);
        prisonerMain.setNativecou(nativecouNameCodeId);
        prisonerMain.setNativevill(nativevillNameCodeId);
        if(StringUtils.isNotBlank(nativeproNameCodeId)) {
            areaNames = areaCodeFullMapper.getAreaNames(nativeproNameCodeId,nativecityNameCodeId,nativecouNameCodeId,nativevillNameCodeId);
            if(areaNames == null) {
                return Result.failure(ReturnCode.SAVE_FAILED);
            }
            prisonerMain.setNativeproName(areaNames.get("shengName"));
            prisonerMain.setNativecityName(areaNames.get("dishiName"));
            prisonerMain.setNativecouName(areaNames.get("quxianName"));
            prisonerMain.setNativevillName(areaNames.get("jiedaoName"));
            if(StringUtils.isBlank(nativecityNameCodeId)) {
                prisonerMain.setNativecityName("");
            }
            if(StringUtils.isBlank(nativecouNameCodeId)) {
                prisonerMain.setNativecouName("");
            }
            if(StringUtils.isBlank(nativevillNameCodeId)) {
                prisonerMain.setNativevillName("");
            }
        } else {
            prisonerMain.setNativeproName("");
            prisonerMain.setNativecityName("");
            prisonerMain.setNativecouName("");
            prisonerMain.setNativevillName("");
        }
        prisonerMain.setNativenum(nativenum);
        boolean tag = prisonerMain.insertOrUpdate();
        Map<String,String> mapTem = new HashMap<>(16);
        mapTem.put("id",prisonerMain.getId());
        mapTem.put("priNum",prisonerMain.getPriNum());
        if(tag) {
            return Result.success(mapTem);
        }
        return Result.failure(ReturnCode.SAVE_FAILED);
    }

    /**
     * 更新核查状态
     * @param priNum 服刑人员编号
     * @param state 更改状态
     */
    @Override
    public void updateStateI(String priNum,String state) {
        prisonerMainMapper.updateStateByPrinum(priNum,state);
    }

    /**
     * 保存出监评估信息
     * @param map 业务数据
     * @return Result
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result insertCjpg(Map<String,Object> map) {
        PrisonerCjpg prisonerCjpg = new PrisonerCjpg();
        prisonerCjpg.setId(IdGen.strid());
        prisonerCjpg.setPriNum(map.get("priNum").toString());
        //是否残疾
        prisonerCjpg.setCanji((String)map.get("canji"));
        //是否吸毒
        prisonerCjpg.setXd((String)map.get("xd"));
        //有无固定住所
        prisonerCjpg.setGdzs((String)map.get("gdzs"));
        //社会交往
        prisonerCjpg.setShjw((String)map.get("shjw"));
        //刑释后可能遇到的困难
        prisonerCjpg.setXshkn((String)map.get("xshkn"));
        //家庭情况
        prisonerCjpg.setJtbh((String)map.get("jtbh"));
        //救助建议
        prisonerCjpg.setJiuzhujianyi((String)map.get("jiuzhujianyi"));
        //是否有违法犯罪倾向
        prisonerCjpg.setSfywffzqx((String)map.get("weifa"));
        //添加时间和添加用户
        String userDtoStr = map.get("userDTO").toString();
        UserDTO userDto = JsonUtil.toBean(userDtoStr,UserDTO.class);
        Date date = new Date();
        prisonerCjpg.setCreateUser(userDto.getAccount());
        prisonerCjpg.setCreateTime(date);
        prisonerCjpg.setUpdateUser(userDto.getAccount());
        prisonerCjpg.setUpdateTime(date);
        boolean insert = prisonerCjpg.insert();
        Map<String,Object> resultMap = new HashMap<>(16);
        resultMap.put("id",prisonerCjpg.getId());
        if(insert) {
            return Result.success(resultMap);
        }
        return Result.failure(ReturnCode.SAVE_FAILED);
    }

    /**
     * 预安置管理 - 预释放人员衔接 - (补录信息、待衔接、衔接中、已衔接、衔接失败) - 列表数据
     * @param user 当前登录用户
     * @param searchmap 搜索条件
     * @param prisonerXjxxInVo 搜索条件
     * @return String
     */
    @Override
    public String getXxblList(UserDTO user,Map<String,Object> searchmap,PrisonerXjxxInVo prisonerXjxxInVo) {
        // 用于区分山西与其他省份
        String localCode = CodeUrlUtils.getLocalCode();
        prisonerXjxxInVo.setPrison(user.getDepartid());
        prisonerXjxxInVo.setStateXj((String)searchmap.get("stateXj"));
        prisonerXjxxInVo.setLevel(user.getLevel());
        searchmap.put("departid",user.getDepartid());
        List<String> qitaKey = null;
        String qitaKeyStr = (String)searchmap.get("qitaKey");
        if(StringUtils.isNotBlank(qitaKeyStr)) {
            String[] split = qitaKeyStr.split(",");
            qitaKey = Arrays.asList(split);
        }
        prisonerXjxxInVo.setOrgid(user.getOrgid());
        searchmap.put("qitaKey",qitaKey);
        if(StringUtils.isNotBlank((String)searchmap.get("shenKey"))) {
            searchmap.put("shenKey",Sm4.encryptEcb((String)searchmap.get("shenKey")));
        }
        //根据level组装转换参数
        Map<String,Object> paramMap = AssemblyConversionUtils.transferAssembly(user.getLevel());
        searchmap.putAll(paramMap);
        Page<Map<String,String>> page = new Page<>(Integer.parseInt(String.valueOf(searchmap.get("pageIndex"))) + 1,Integer.parseInt(String.valueOf(searchmap.get("pageSize"))));
        List<Map<String,String>> data = prisonerMainMapper.getXxblList(page,prisonerXjxxInVo,searchmap,localCode);
        //把监狱与和对应的省份匹配
        Map<Object,Object> mapProvince = stringRedisTemplate.opsForHash().entries("province");
        for(Map<String,String> item : data) {
            //这里SQL返回的不一致，需要判断
            if(StringUtils.isEmpty(item.get("prisonName"))) {
                item.put("prisonName","");
            } else if(mapProvince.get(item.get("priNum").substring(0,2) + "0000") != null) {
                item.put("prisonName",mapProvince.get(item.get("priNum")
                                                          .substring(0,2) + "0000") + "-" + item.get("prisonName"));
            }
            if(StringUtils.isEmpty(item.get("pdanweiName"))) {
                item.put("pdanweiName","");
            } else if(mapProvince.get(item.get("priNum").substring(0,2) + "0000") != null) {
                item.put("pdanweiName",mapProvince.get(item.get("priNum")
                                                           .substring(0,2) + "0000") + "-" + item.get("pdanweiName"));
            }
        }
        page.setRecords(data);
        searchmap.put("total",data.size());
        CompletableFuture.runAsync(() -> {
            log.info("工作台-预释放人员衔接-异步条件进入redis {}:" + Thread.currentThread().getName());
            ConditionUtils.searchConditions(searchmap,user.getAccount(),redisTemplate);
        });
        return PageReturnUtil.pageReturn(page);
    }

    /**
     * 根据犯罪编号查询罪犯基本信息
     * @param prinum 犯罪编号
     * @return String
     */
    @Override
    public String getInmateInfo(String prinum) {
        PrisonerMain prisonerMain = prisonerMainMapper.selectById(prinum);
        AbLieguan abLieguan = abLieguanMapper.selectById(prinum);
        String tuJing = prisonerXjxxMapper.findTuJing(prinum);
        String prinumstr = prisonerMain.getPriNum();
        String idstr = prisonerMain.getId();
        String idNumStr = null == prisonerMain.getIdNum() ? "" : prisonerMain.getIdNum();
        String mainText = JsonUtil.toText(prisonerMain);
        Map<String,Object> mainMap = JsonUtil.toMap(mainText);
        mainMap.put("priNum",prinumstr);
        mainMap.put("id",idstr);
        mainMap.put("idNum",idNumStr);
        if(null != abLieguan && StringUtils.isNotBlank(abLieguan.getShenStatef())) {
            mainMap.put("slgspStatef",abLieguan.getShenStatef());
        }
        mainMap.put("tujing",tuJing);
        if(Constants.NumberStr.NUM_STR_ZERO_TWO.equals(prisonerMain.getHjType())) {
            mainMap.put("investigatePro",prisonerMain.getInvestigatePro());
            mainMap.put("investigateCity",prisonerMain.getInvestigateCity());
            mainMap.put("investigateCou",prisonerMain.getInvestigateCou());
            mainMap.put("investigateVill",prisonerMain.getInvestigateVill());
            mainMap.put("investigateProName",prisonerMain.getInvestigateProName());
            mainMap.put("investigateCityName",prisonerMain.getInvestigateCityName());
            mainMap.put("investigateCouName",prisonerMain.getInvestigateCouName());
            mainMap.put("investigateVillName",prisonerMain.getInvestigateVillName());
            mainMap.put("investigateNum",prisonerMain.getInvestigateNum());
        }
        if(!StringUtils.isEmpty(prisonerMain.getPdanwei())) {
            SystemCode systemCode = getAdminCodeById(prisonerMain.getPdanwei().substring(0,2) + "0000");
            mainMap.put("addProvince",systemCode.getCodeName());
            mainMap.put("codeId",systemCode.getCodeId());
        }
        return JsonUtil.toText(mainMap);
    }

    /**
     * 根据犯罪编号查询罪犯基本信息 - excel
     * @param prinum 犯罪编号
     * @return String
     */
    @Override
    public String getInmateInfoExcel(String prinum) {
        PrisonerMainExcelTemp prisonerMain = prisonerMainExcelTempMapper.selectById(prinum);
        String prinumstr = prisonerMain.getPriNum();
        String idstr = prisonerMain.getId();
        String idNumStr = "";
        if(null != prisonerMain.getIdNum()) {
            if(prisonerMain.getIdNum().length() > 18) {
                idNumStr = Sm4.decryptEcb(prisonerMain.getIdNum());
            } else {
                idNumStr = prisonerMain.getIdNum();
            }
        }
        String mainText = JsonUtil.toText(prisonerMain);
        Map<String,Object> mainMap = JsonUtil.toMap(mainText);
        mainMap.put("priNum",prinumstr);
        mainMap.put("id",idstr);
        mainMap.put("idNum",idNumStr);
        String tuJing = prisonerXjxxMapper.findTuJing(prinum);
        mainMap.put("tujing",tuJing);
        if(!StringUtils.isEmpty(prisonerMain.getPdanwei())) {
            SystemCode systemCode = getAdminCodeById(prisonerMain.getPdanwei().substring(0,2) + "0000");
            mainMap.put("addProvince",systemCode.getCodeName());
            mainMap.put("codeId",systemCode.getCodeId());
        }
        return JsonUtil.toText(mainMap);
    }

    /**
     * 预安置管理 - 预安置人员信息录入 - 删除(逻辑删除)
     * @param prinum 犯罪编号
     * @return Result
     */
    @Override
    public Result removeListBaseInfo(String prinum) {
        int row = prisonerMainMapper.updateDelFlagByPrinum(prinum);
        if(0 < row) {
            return Result.success("删除成功");
        }
        return Result.failure(ReturnCode.DELETE_FAILED);
    }

    /**
     * 预安置管理 - 预安置人员信息录入 - 批量导入 - 删除(逻辑删除)
     * @param prinum 犯罪编号
     * @return Result
     */
    @Override
    public Result removeListBaseInfoExcel(String prinum) {
        int row = prisonerMainExcelTempMapper.updateDelFlagByPrinum(prinum);
        if(0 < row) {
            return Result.success("删除成功");
        }
        return Result.failure(ReturnCode.DELETE_FAILED);
    }

    /**
     * 预安置管理 - 预安置人员信息录入 - 批量导入 - 批量删除(逻辑删除)
     * @param prinumLists 罪犯编号
     * @return Result
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result removeListBaseInfoExcels(List<String> prinumLists) {
        int row = prisonerMainExcelTempMapper.updateDelFlagByPrinums(prinumLists);
        if(0 < row) {
            return Result.success("删除成功");
        }
        return Result.failure(ReturnCode.DELETE_FAILED);
    }

    /**
     * 信息补录 - 发起衔接 - 衔接信息 - 保存
     * @param data 业务数据
     * @param departid 部门Id
     * @param departName 部门名称
     * @param account 账号
     * @return int 受影响行数
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result insertXjxx(String data,String departid,String departName,String account) {
        PrisonerXixxVo entity = JsonUtil.toBean(data,PrisonerXixxVo.class);
        Date date1 = new Date();
        //修改主表衔接状态
        try {
            PrisonerMain prisonerMain = new PrisonerMain();
            prisonerMain.setUpdateUser(account);
            prisonerMain.setUpdateTime(date1);
            prisonerMain.setId(entity.getId());
            prisonerMain.setPriNum(entity.getPriNum());
            prisonerMain.setStateXj(Constants.NumberStr.NUM_STR_TWO);
            prisonerMainMapper.updatePrisonerMainById(prisonerMain);
            PrisonerMain prisonerMain1 = prisonerMainMapper.selectPrisonerMain((entity.getPriNum()));
            String sfsId = prisonerMain1.getNativevill();
            String sfsName = prisonerMain1.getNativevillName();
            //衔接表
            PrisonerXjxx prisonerXjx = new PrisonerXjxx();
            prisonerXjx.setId(IdGen.strid());
            prisonerXjx.setPriNum(entity.getPriNum());
            prisonerXjx.setTujing(entity.getTujing());
            prisonerXjx.setType(entity.getType());
            prisonerXjx.setYiban(entity.getYiban());
            prisonerXjx.setZhongdian(entity.getZhongdian());
            prisonerXjx.setLianxiren(entity.getLianxiren());
            prisonerXjx.setDianhua(entity.getDianhua());
            prisonerXjx.setJhsj(entity.getJhsj());
            prisonerXjx.setJhdd(entity.getJhdd());
            prisonerXjx.setAdduserid(departid);
            prisonerXjx.setAddusername(departName);
            //添加时间和添加用户
            prisonerXjx.setCreateUser(account);
            prisonerXjx.setCreateTime(date1);
            prisonerXjx.setUpdateUser(account);
            prisonerXjx.setUpdateTime(date1);
            prisonerXjxxService.save(prisonerXjx);
            //衔接的同时生成一条回执中间表数据
            XjReceipt xjReceipt = new XjReceipt();
            xjReceipt.setXjid(IdGen.strid());
            xjReceipt.setPriNum(prisonerXjx.getPriNum());
            xjReceipt.setSendCode(prisonerXjx.getAdduserid());
            xjReceipt.setSendName(prisonerXjx.getAddusername());
            xjReceipt.setReceiveCode(null == sfsId ? "" : sfsId);
            xjReceipt.setReceiveName(null == sfsName ? "" : sfsName);
            xjReceipt.setSessionFlag(Constants.NumberStr.NUM_STR_ZERO);
            xjReceipt.setFlag(Constants.NumberStr.NUM_STR_TWO);
            xjReceipt.setCreateTime(date1);
            xjReceipt.setUpdateTime(date1);
            xjReceipt.setCreateUser(account);
            xjReceipt.setUpdateUser(account);
            xjReceiptMapper.saveXjReceive(xjReceipt);
            //保存信息表
            String xjid = xjReceipt.getXjid();
            XjReceiptData xjReceiptData = new XjReceiptData();
            xjReceiptData.setSessionId(xjid);
            xjReceiptData.setLiaisonMan(entity.getLianxiren());
            xjReceiptData.setLiaisonPhone(entity.getDianhua());
            xjReceiptData.setTakebackTime(entity.getJhsj());
            xjReceiptData.setTakebackAddress(entity.getJhdd());
            xjReceiptData.setOwnerFlag(Constants.NumberStr.NUM_STR_ONE);
            xjReceiptData.setCreateUser(account);
            xjReceiptData.setUpdateUser(account);
            xjReceiptData.setCreateTime(date1);
            xjReceiptData.setUpdateTime(date1);
            xjReceiptDataVoMapper.saveXjReceiveMessage(xjReceiptData);
        } catch(RuntimeException e) {
            log.error("发生异常：",e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.failure(ReturnCode.FAILURE);
        }
        return Result.success();
    }

    /**
     * 预安置管理 - 预释放人员衔接 - 衔接中 - 回执
     * @param data 业务数据
     * @param account 账号
     * @param level level
     * @return String
     */
    @Override
    public String saveXjHzMessage(String data,String account,String level) {
        //01 监狱 02 看守所 03 司法所 04 未管所 05 社区服刑 06 司法厅 07 地市司法局 08 区县司法局 09 监狱局
        String ownerFlag = "";
        if(Constants.NumberStr.NUM_STR_ZERO_THREE.equals(level)) {
            //司法所
            ownerFlag = Constants.NumberStr.NUM_STR_TWO;
        }
        if(Constants.NumberStr.NUM_STR_ZERO_ONE.equals(level)) {
            //监狱
            ownerFlag = Constants.NumberStr.NUM_STR_ONE;
        }
        if(Constants.NumberStr.NUM_STR_ZERO_FIVE.equals(level)) {
            //社矫
            ownerFlag = Constants.NumberStr.NUM_STR_FIVE;
        }
        if(Constants.NumberStr.NUM_STR_ZERO_TWO.equals(level)) {
            //看守所标志
            ownerFlag = Constants.NumberStr.NUM_STR_THREE;
        }
        if(Constants.NumberStr.NUM_STR_ZERO_EIGHT.equals(level)) {
            //区县司法局标识
            ownerFlag = Constants.NumberStr.NUM_STR_ZERO_EIGHT;
        }
        if(Constants.NumberStr.NUM_STR_ZERO_SEVEN.equals(level)) {
            //地市司法局标识
            ownerFlag = Constants.NumberStr.NUM_STR_ZERO_SEVEN;
        }
        if(Constants.NumberStr.NUM_STR_ZERO_SIX.equals(level)) {
            //司法厅标识
            ownerFlag = Constants.NumberStr.NUM_STR_ZERO_SIX;
        }
        JSONObject json = JSON.parseObject(data);
        Date date = new Date();
        String priNum = (String)json.get("priNum");
        XjReceiptData xjReceiptData = JsonUtil.toBean(data,XjReceiptData.class);
        if(json.containsKey("xjrctId")) {
            // 核查流程中查询xjid
            String xjrctId = (String)json.get("xjrctId");
            String xjid = xjReceiptMapper.selectHcReceive(priNum,xjrctId);
            // 如果xjid为null则说明旧数据
            if(StringUtils.isBlank(xjid)) {
                LiuChengHcAndMainVo liuChengHcAndMain = liuChengOldDataMapper.hcWc(priNum);
                //核查流程回执老数据插入数据
                xjid = wcHc(liuChengHcAndMain);
            }
            xjReceiptData.setSessionId(xjid);
        } else { 
            // 衔接流程中查询xjid
            String xjid = xjReceiptMapper.selectXjReceive(priNum);
            xjReceiptData.setSessionId(xjid);
        }
        xjReceiptData.setCreateUser(account);
        xjReceiptData.setUpdateTime(date);
        xjReceiptData.setUpdateUser(account);
        xjReceiptData.setOwnerFlag(ownerFlag);
        xjReceiptData.setCreateTime(date);
        int i = xjReceiptDataVoMapper.saveXjReceiveMessage(xjReceiptData);
        boolean flag = Constants.Number.NUM_ZERO < i && (Constants.NumberStr.NUM_STR_ZERO_ONE.equals(level) || Constants.NumberStr.NUM_STR_ZERO_TWO.equals(level) || Constants.NumberStr.NUM_STR_ZERO_FIVE.equals(level));
        if(flag) {
            prisonerXjxxMapper.updateXjxx(xjReceiptData.getTakebackTime(),xjReceiptData.getTakebackAddress(),xjReceiptData.getLiaisonMan(),xjReceiptData.getLiaisonPhone(),priNum);
        }
        //根据犯罪编号查询是否需要同步到第三省份
        InterProvincialBusiness info = businessMapper.findInfo(priNum);
        if(null != info && null != info.getDssftDepartid() && null != info.getDssftszsOld() && !info.getDssftDepartid()
                                                                                                    .equals(info.getDssftszsOld())) {
            //本系统的本地code
            String localCode = CodeUrlUtils.getLocalCode();
            if(!localCode.equals(info.getDssftDepartid())) {
                String prisonerXjxxDeleteSql = "delete from prisoner_xjxx where pri_num='" + priNum + "'";
                String xjReceiptDeleteSql = "delete from xj_receipt where pri_num='" + priNum + "'";
                String xjReceiptDataDeleteSql = "delete from xj_receipt_data where session_id in (select xjid from xj_receipt where pri_num ='" + priNum + "')";
                List<String> prisonerXjxxInsertSql = JdbcUtils.getInsertSql("prisoner_xjxx","pri_num",priNum,null,null,null,null);
                List<String> xjReceiptInsertSql = JdbcUtils.getInsertSql("xj_receipt","pri_num",priNum,null,null,null,null);
                List<String> xjReceiptDataInsertSql = JdbcUtils.getInsertSql("xj_receipt_data","session_id",priNum,null,null,null,null);
                String middleSql13 = JdbcUtils.createMiddleSql(priNum,prisonerXjxxDeleteSql,Constants.Number.NUM_ZERO,localCode,info.getDssftDepartid());
                middleJdbcTemplate.update(middleSql13);
                String middleSql14 = JdbcUtils.createMiddleSql(priNum,xjReceiptDeleteSql,Constants.Number.NUM_ZERO,localCode,info.getDssftDepartid());
                middleJdbcTemplate.update(middleSql14);
                String middleSql15 = JdbcUtils.createMiddleSql(priNum,xjReceiptDataDeleteSql,Constants.Number.NUM_ZERO,localCode,info.getDssftDepartid());
                middleJdbcTemplate.update(middleSql15);
                for(String sql : prisonerXjxxInsertSql) {
                    String isql = JdbcUtils.createMiddleSql(priNum,sql,Constants.Number.NUM_ZERO,localCode,info.getDssftDepartid());
                    middleJdbcTemplate.update(isql);
                }
                for(String sql : xjReceiptInsertSql) {
                    String isql = JdbcUtils.createMiddleSql(priNum,sql,Constants.Number.NUM_ZERO,localCode,info.getDssftDepartid());
                    middleJdbcTemplate.update(isql);
                }
                for(String sql : xjReceiptDataInsertSql) {
                    String isql = JdbcUtils.createMiddleSql(priNum,sql,Constants.Number.NUM_ZERO,localCode,info.getDssftDepartid());
                    middleJdbcTemplate.update(isql);
                }
            }
        }
        return xjReceiptData.getSessionId();
    }

    /**
     * 为旧数据回执添加默认值
     * @param liuChengHcAndMainVo liuChengHcAndMainVo
     * @return String xjid
     */
    private String wcHc(LiuChengHcAndMainVo liuChengHcAndMainVo) {
        Date date = new Date();
        //随机生成推送的id
        String tsId = IdGen.strid();
        //每次给ts表的id给予默认值
        liuChengHcAndMainVo.setTsId(tsId);
        liuChengOldDataMapper.insertTs(liuChengHcAndMainVo);
        //修改核查表的xjrct_id为推送的ID
        liuChengOldDataMapper.updateHcXjrctId(tsId,liuChengHcAndMainVo.getPriNum());
        String priNum = liuChengHcAndMainVo.getPriNum();
        String addUserId = liuChengHcAndMainVo.getAdduserId();
        String addUserName = liuChengHcAndMainVo.getAdduserName();
        String pDanWei = liuChengHcAndMainVo.getPDanWei();
        String pDanWeiName = liuChengHcAndMainVo.getPDanWeiName();
        String createUser = liuChengHcAndMainVo.getCreateUser();
        String updateUser = liuChengHcAndMainVo.getUpdateUser();
        XjReceipt xjReceipt = new XjReceipt();
        //录入监所和服刑单位都没有--情况很少
        boolean flag = (null == addUserId || Constants.Number.NUM_ZERO == addUserId.length()) && (null == pDanWei || Constants.Number.NUM_ZERO == pDanWei.length());
        if(flag) {
            xjReceipt.setCreateUser("默认");
            xjReceipt.setUpdateUser("默认");
            xjReceipt.setSendCode("默认");
            xjReceipt.setSendName("默认");
        } else {
            //录入监所addUserId为空
            if(null == addUserId || "".equals(addUserId)) {
                //创建用户为null
                if(null == createUser || "".equals(createUser)) {
                    //根据pdanwei查询出来对应的账号
                    String account = liuChengOldDataMapper.selectAccount(pDanWei);
                    //处理外省的addUserId和pdanwei
                    if(null == account || Constants.Number.NUM_ZERO == account.length()) {
                        xjReceipt.setCreateUser("默认");
                        xjReceipt.setUpdateUser("默认");
                        xjReceipt.setSendCode(pDanWei);
                        //判断录入监所名称和服刑单位名称是否为null
                        boolean flag1 = null == addUserName || Constants.Number.NUM_ZERO == addUserName.length();
                        boolean flag2 = null == pDanWeiName || Constants.Number.NUM_ZERO == pDanWeiName.length();
                        if(flag1 && flag2) {
                            xjReceipt.setSendName("默认");
                        } else {
                            if(null == addUserName || Constants.Number.NUM_ZERO == addUserName.length()) {
                                xjReceipt.setSendName(pDanWeiName);
                            } else {
                                xjReceipt.setSendName(addUserName);
                            }
                        }
                    } else {
                        //处理本省的数据
                        xjReceipt.setCreateUser(account);
                        xjReceipt.setUpdateUser(account);
                        xjReceipt.setSendCode(pDanWei);
                        //判断录入监所名称是否为null
                        if(null == addUserName || Constants.Number.NUM_ZERO == addUserName.length()) {
                            xjReceipt.setSendName(pDanWeiName);
                        } else {
                            xjReceipt.setSendName(addUserName);
                        }
                    }
                } else if(null == updateUser || "".equals(updateUser)) {
                    //根据pdanwei查询出来对应的账号
                    String account = liuChengOldDataMapper.selectAccount(pDanWei);
                    //处理外省的addUserId和pdanwei
                    if(null == account || Constants.Number.NUM_ZERO == account.length()) {
                        xjReceipt.setCreateUser("默认");
                        xjReceipt.setUpdateUser("默认");
                        xjReceipt.setSendCode(pDanWei);
                        //判断录入监所名称和服刑单位名称是否为null
                        boolean flag3 = null == addUserName || Constants.Number.NUM_ZERO == addUserName.length();
                        boolean flag4 = null == pDanWeiName || Constants.Number.NUM_ZERO == pDanWeiName.length();
                        if(flag3 && flag4) {
                            xjReceipt.setSendName("默认");
                        } else {
                            if(null == addUserName || Constants.Number.NUM_ZERO == addUserName.length()) {
                                xjReceipt.setSendName(pDanWeiName);
                            } else {
                                xjReceipt.setSendName(addUserName);
                            }
                        }
                    } else {
                        //处理本省的数据
                        xjReceipt.setCreateUser(account);
                        xjReceipt.setUpdateUser(account);
                        xjReceipt.setSendCode(pDanWei);
                        //判断录入监所名称是否为null
                        if(null == addUserName || Constants.Number.NUM_ZERO == addUserName.length()) {
                            xjReceipt.setSendName(pDanWeiName);
                        } else {
                            xjReceipt.setSendName(addUserName);
                        }
                    }
                } else {
                    //根据pdanwei查询出来对应的账号
                    String account = liuChengOldDataMapper.selectAccount(pDanWei);
                    //处理外省的addUserId和pdanwei
                    if(null == account || Constants.Number.NUM_ZERO == account.length()) {
                        xjReceipt.setCreateUser("默认");
                        xjReceipt.setUpdateUser("默认");
                        xjReceipt.setSendCode(pDanWei);
                        //判断录入监所名称和服刑单位名称是否为null
                        if(null == addUserName && null == pDanWeiName) {
                            xjReceipt.setSendName("默认");
                        } else {
                            if(null == addUserName) {
                                xjReceipt.setSendName(pDanWeiName);
                            } else {
                                xjReceipt.setSendName(addUserName);
                            }
                        }
                    } else {
                        //处理本省的数据
                        xjReceipt.setCreateUser(createUser);
                        xjReceipt.setUpdateUser(updateUser);
                        xjReceipt.setSendCode(pDanWei);
                        //判断录入监所名称是否为null
                        if(null == addUserName || Constants.Number.NUM_ZERO == addUserName.length()) {
                            xjReceipt.setSendName(pDanWeiName);
                        } else {
                            xjReceipt.setSendName(addUserName);
                        }
                    }
                }
            } else if(null == pDanWei || "".equals(pDanWei)) {
                //创建用户为null
                if(null == createUser || "".equals(createUser)) {
                    //根据addUserId查询出来对应的账号
                    String account = liuChengOldDataMapper.selectAccount(addUserId);
                    //处理外省的addUserId和pdanwei
                    if(null == account || Constants.Number.NUM_ZERO == account.length()) {
                        xjReceipt.setCreateUser("默认");
                        xjReceipt.setUpdateUser("默认");
                        xjReceipt.setSendCode(addUserId);
                        //判断录入监所名称和服刑单位名称是否为null
                        if(null == addUserName && null == pDanWeiName) {
                            xjReceipt.setSendName("默认");
                        } else {
                            if(null == addUserName) {
                                xjReceipt.setSendName(pDanWeiName);
                            } else {
                                xjReceipt.setSendName(addUserName);
                            }
                        }
                    } else {
                        //处理本省的数据
                        xjReceipt.setCreateUser(account);
                        xjReceipt.setUpdateUser(account);
                        xjReceipt.setSendCode(addUserId);
                        //判断录入监所名称是否为null
                        if(null == addUserName || Constants.Number.NUM_ZERO == addUserName.length()) {
                            xjReceipt.setSendName(pDanWeiName);
                        } else {
                            xjReceipt.setSendName(addUserName);
                        }
                    }
                } else if(null == updateUser || "".equals(updateUser)) {
                    //根据addUserId查询出来对应的账号
                    String account = liuChengOldDataMapper.selectAccount(pDanWei);
                    //处理外省的addUserId和pdanwei
                    if(null == account || Constants.Number.NUM_ZERO == account.length()) {
                        xjReceipt.setCreateUser("默认");
                        xjReceipt.setUpdateUser("默认");
                        xjReceipt.setSendCode(addUserId);
                        //判断录入监所名称和服刑单位名称是否为null
                        if(null == addUserName && null == pDanWeiName) {
                            xjReceipt.setSendName("默认");
                        } else {
                            if(null == addUserName) {
                                xjReceipt.setSendName(pDanWeiName);
                            } else {
                                xjReceipt.setSendName(addUserName);
                            }
                        }
                    } else {
                        //处理本省的数据
                        xjReceipt.setCreateUser(account);
                        xjReceipt.setUpdateUser(account);
                        xjReceipt.setSendCode(addUserId);
                        //判断录入监所名称是否为null
                        if(null == addUserName || Constants.Number.NUM_ZERO == addUserName.length()) {
                            xjReceipt.setSendName(pDanWeiName);
                        } else {
                            xjReceipt.setSendName(addUserName);
                        }
                    }
                } else {
                    //根据pdanwei查询出来对应的账号
                    String account = liuChengOldDataMapper.selectAccount(pDanWei);
                    //处理外省的addUserId和pdanwei
                    if(null == account || Constants.Number.NUM_ZERO == account.length()) {
                        xjReceipt.setCreateUser("默认");
                        xjReceipt.setUpdateUser("默认");
                        xjReceipt.setSendCode(addUserId);
                        //判断录入监所名称和服刑单位名称是否为null
                        if(null == addUserName && null == pDanWeiName) {
                            xjReceipt.setSendName("默认");
                        } else {
                            if(null == addUserName) {
                                xjReceipt.setSendName(pDanWeiName);
                            } else {
                                xjReceipt.setSendName(addUserName);
                            }
                        }
                    } else {
                        //处理本省的数据
                        xjReceipt.setCreateUser(createUser);
                        xjReceipt.setUpdateUser(updateUser);
                        xjReceipt.setSendCode(pDanWei);
                        //判断录入监所名称是否为null
                        if(null == addUserName || Constants.Number.NUM_ZERO == addUserName.length()) {
                            xjReceipt.setSendName(pDanWeiName);
                        } else {
                            xjReceipt.setSendName(addUserName);
                        }
                    }
                }
            }
        }
        //addUserId/pdanwei都不是空
        if(null != addUserId && null != pDanWei) {
            //创建用户为null
            if(null == createUser || "".equals(createUser)) {
                //根据addUserId查询出来对应的账号
                String account = liuChengOldDataMapper.selectAccount(addUserId);
                //处理外省的addUserId和pdanwei
                if(null == account || Constants.Number.NUM_ZERO == account.length()) {
                    xjReceipt.setCreateUser("默认");
                    xjReceipt.setUpdateUser("默认");
                    xjReceipt.setSendCode(addUserId);
                    //判断录入监所名称和服刑单位名称是否为null
                    if(null == addUserName && null == pDanWeiName) {
                        xjReceipt.setSendName("默认");
                    } else {
                        if(null == addUserName) {
                            xjReceipt.setSendName(pDanWeiName);
                        } else {
                            xjReceipt.setSendName(addUserName);
                        }
                    }
                } else {
                    //处理本省的数据
                    xjReceipt.setCreateUser(account);
                    xjReceipt.setUpdateUser(account);
                    xjReceipt.setSendCode(addUserId);
                    //判断录入监所名称是否为null
                    if(null == addUserName || Constants.Number.NUM_ZERO == addUserName.length()) {
                        xjReceipt.setSendName(pDanWeiName);
                    } else {
                        xjReceipt.setSendName(addUserName);
                    }
                }
            } else if(null == updateUser || "".equals(updateUser)) {
                //根据addUserId查询出来对应的账号
                String account = liuChengOldDataMapper.selectAccount(pDanWei);
                //处理外省的addUserId和pdanwei
                if(null == account || Constants.Number.NUM_ZERO == account.length()) {
                    xjReceipt.setCreateUser("默认");
                    xjReceipt.setUpdateUser("默认");
                    xjReceipt.setSendCode(addUserId);
                    //判断录入监所名称和服刑单位名称是否为null
                    if(null == addUserName && null == pDanWeiName) {
                        xjReceipt.setSendName("默认");
                    } else {
                        if(null == addUserName) {
                            xjReceipt.setSendName(pDanWeiName);
                        } else {
                            xjReceipt.setSendName(addUserName);
                        }
                    }
                } else {
                    //处理本省的数据
                    xjReceipt.setCreateUser(account);
                    xjReceipt.setUpdateUser(account);
                    xjReceipt.setSendCode(addUserId);
                    //判断录入监所名称是否为null
                    if(null == addUserName || Constants.Number.NUM_ZERO == addUserName.length()) {
                        xjReceipt.setSendName(pDanWeiName);
                    } else {
                        xjReceipt.setSendName(addUserName);
                    }
                }
            } else {
                //根据pdanwei查询出来对应的账号
                String account = liuChengOldDataMapper.selectAccount(pDanWei);
                //处理外省的addUserId和pdanwei
                if(null == account || Constants.Number.NUM_ZERO == account.length()) {
                    xjReceipt.setCreateUser("默认");
                    xjReceipt.setUpdateUser("默认");
                    xjReceipt.setSendCode(addUserId);
                    //判断录入监所名称和服刑单位名称是否为null
                    if(null == addUserName && null == pDanWeiName) {
                        xjReceipt.setSendName("默认");
                    } else {
                        if(null == addUserName) {
                            xjReceipt.setSendName(pDanWeiName);
                        } else {
                            xjReceipt.setSendName(addUserName);
                        }
                    }
                } else {
                    //处理本省的数据
                    xjReceipt.setCreateUser(updateUser);
                    xjReceipt.setUpdateUser(createUser);
                    xjReceipt.setSendCode(pDanWei);
                    //判断录入监所名称是否为null
                    if(null == addUserName || Constants.Number.NUM_ZERO == addUserName.length()) {
                        xjReceipt.setSendName(pDanWeiName);
                    } else {
                        xjReceipt.setSendName(addUserName);
                    }
                }
            }
        }
        //给xj_receipt表赋予默认值
        xjReceipt.setXjid(tsId);
        xjReceipt.setPriNum(priNum);
        xjReceipt.setReceiveCode(liuChengHcAndMainVo.getNativeVill());
        xjReceipt.setReceiveName(liuChengHcAndMainVo.getNativeVillName());
        xjReceipt.setSessionFlag(Constants.NumberStr.NUM_STR_ZERO);
        xjReceipt.setCreateTime(date);
        xjReceipt.setUpdateTime(date);
        xjReceipt.setFlag(Constants.NumberStr.NUM_STR_ONE);
        liuChengOldDataMapper.insertXj(xjReceipt);
        return tsId;
    }

    /**
     * 预安置管理 - 预释放人员衔接 - 衔接中 - 查看回执列表数据
     * @param priNum 服刑人员编号
     * @return List<XjReceiptDataVo>
     */
    @Override
    public List<XjReceiptDataVo> findMessages(String priNum,String xjrctId) {
        //根据sessionID查询出消息表数据
        List<XjReceiptDataVo> xjReceiptDataVos;
        if(Constants.NumberStr.NUM_STR_FU_ONE.equals(xjrctId)) {
            // 衔接流程或者老数据的查询回执消息
            xjReceiptDataVos = xjReceiptDataVoMapper.selectXjReceiveMessagesBySessionId(priNum);
        } else {
            // 核查流程的查询回执消息
            xjReceiptDataVos = xjReceiptMapper.selectHcReceiveMessage(priNum,xjrctId);
        }
        for(XjReceiptDataVo vo : xjReceiptDataVos) {
            Map<String,String> dianhua = PhoneUtil.splitTelAndPhone(vo.getLiaisonPhone());
            vo.setLiaisonPhone(dianhua.get("phone"));
            vo.setLiaisonTel(dianhua.get("tel"));
        }
        return xjReceiptDataVos;
    }

    /**
     * 预安置管理 - 预释放人员衔接 - 查看 - 档案材料
     * @param paramMap 查询参数
     * @return PrisonerXixxVo
     */
    @Override
    public PrisonerXixxVo xjxxJsonData(Map<String,Object> paramMap) {
        return prisonerXjxxMapper.selectPrisonerXjxxByPriNum(paramMap);
    }

    /**
     * 预安置管理 - 预释放人员衔接 - 衔接中 - 完成衔接 - 保存
     * @param data 业务数据
     * @param userDTO 当前登录用户
     * @return Result
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result updateCompletelyData(String data,UserDTO userDTO) {
        PrisonerXixxVo entity = JsonUtil.toBean(data,PrisonerXixxVo.class);
        Date date1 = new Date();
        PrisonerMain prisonerMain = new PrisonerMain();
        prisonerMain.setUpdateUser(userDTO.getAccount());
        prisonerMain.setUpdateTime(date1);
        PrisonerXjxx prisonerXjxx = new PrisonerXjxx();
        prisonerXjxx.setId(entity.getId());
        prisonerXjxx.setUpdateUser(userDTO.getAccount());
        prisonerXjxx.setGalxr(entity.getGalxr());
        prisonerXjxx.setGalxfs(entity.getGalxfs());
        prisonerXjxx.setPriNum(entity.getPriNum());
        prisonerXjxx.setGongan(entity.getGongan());
        prisonerXjxx.setRemark(entity.getRemark());
        //完成衔接、衔接失败的时间
        prisonerXjxx.setUpdateTime(date1);
        //安置帮教人员类型
        prisonerXjxx.setAbPersonType(entity.getAbPersonType());
        // 1： 成功 3：失败
        if(Constants.NumberStr.NUM_STR_THREE.equals(entity.getStatexj())) {
            prisonerMain.setStateXj(Constants.NumberStr.NUM_STR_THREE);
            prisonerXjxx.setSecondState(Constants.NumberStr.NUM_STR_ZERO);
        } else if(Constants.NumberStr.NUM_STR_ZERO.equals(entity.getSecondStateXj()) && Constants.NumberStr.NUM_STR_ONE.equals(entity.getStatexj())) {
            prisonerXjxx.setSecondStateXj(Constants.NumberStr.NUM_STR_ONE);
        } else if(Constants.NumberStr.NUM_STR_FU_ONE.equals(entity.getSecondStateXj()) && Constants.NumberStr.NUM_STR_ONE.equals(entity.getStatexj())) {
            prisonerMain.setStateXj(entity.getStatexj());
        }
        //判断是否湖南个性化数据
        Result result = interfaceDockingService.getHnInterfaceOppositeByPriNum(entity.getPriNum());
        if(Constants.Number.NUM_ONE.equals(result.getCode())) {
            xjhz(userDTO,entity);
        }
        prisonerXjxxService.updateById(prisonerXjxx);
        PrisonerMain mainParam = prisonerMainMapper.selectPrisonerMain((entity.getPriNum()));
        prisonerMain.setAge(mainParam.getAge() != null ? mainParam.getAge() : null);
        //修改主表衔接状态
        prisonerMain.setPriNum(entity.getPriNum());
        prisonerMainTowService.updateById(prisonerMain);
        //修改回执中间表会话状态
        //根据priNum查询xjid(后期可能除了priNum还需要其他条件)
        String xjid = xjReceiptMapper.selectXjReceive(entity.getPriNum());
        int i = xjReceiptMapper.updateXjReceive(xjid);
        if(Constants.NumberStr.NUM_STR_ONE.equals(entity.getStatexj())) {
            //遍历基本表获取数据,并把数据存入安置表
            prisonerMain = prisonerMainMapper.selectPrisonerMain(entity.getPriNum());
            AbPrisonersResultVo abPrisonersResult = new AbPrisonersResultVo();
            //设置安置帮教人员类型参见code表1_34
            abPrisonersResult.setPriNum(prisonerMain.getPriNum());
            abPrisonersResult.setStateXj(prisonerMain.getStateXj());
            abPrisonersResult.setSex(prisonerMain.getSex());
            abPrisonersResult.setPname(prisonerMain.getPName());
            abPrisonersResult.setUsedname(prisonerMain.getUsedName());
            abPrisonersResult.setNationality(prisonerMain.getNationality());
            abPrisonersResult.setIdnum(Sm4.encryptEcb(prisonerMain.getIdNum()));
            abPrisonersResult.setAge(prisonerMain.getAge());
            abPrisonersResult.setState(prisonerMain.getState());
            abPrisonersResult.setEducation(prisonerMain.getEducation());
            abPrisonersResult.setAdduserid(prisonerMain.getAdduserid());
            abPrisonersResult.setAddusername(prisonerMain.getAddusername());
            abPrisonersResult.setPstate(prisonerMain.getPstate());
            abPrisonersResult.setPtype(prisonerMain.getPtype());
            abPrisonersResult.setPdanwei(prisonerMain.getPdanwei());
            abPrisonersResult.setAddtime(prisonerMain.getAddtime());
            abPrisonersResult.setPriAddr(prisonerMain.getPriAddr());
            abPrisonersResult.setNativepro(prisonerMain.getNativepro());
            abPrisonersResult.setNativeproName(prisonerMain.getNativeproName());
            abPrisonersResult.setNativecity(prisonerMain.getNativecity());
            abPrisonersResult.setNativecityName(prisonerMain.getNativecityName());
            abPrisonersResult.setNativecou(prisonerMain.getNativecou());
            abPrisonersResult.setNativecouName(prisonerMain.getNativecouName());
            abPrisonersResult.setNativevill(prisonerMain.getNativevill());
            abPrisonersResult.setNativevillName(prisonerMain.getNativevillName());
            abPrisonersResult.setNativenum(prisonerMain.getNativenum());
            abPrisonersResult.setArrestcity(prisonerMain.getArrestcity());
            abPrisonersResult.setArrestpro(prisonerMain.getArrestpro());
            abPrisonersResult.setArrestcou(prisonerMain.getArrestcou());
            abPrisonersResult.setArrestvillName(prisonerMain.getArrestvill());
            abPrisonersResult.setArrestvill(prisonerMain.getArrestvill());
            abPrisonersResult.setArrestnum(prisonerMain.getArrestnum());
            abPrisonersResult.setPlacepro(prisonerMain.getPlacepro());
            abPrisonersResult.setPlaceproName(prisonerMain.getPlaceproName());
            abPrisonersResult.setPlacecity(prisonerMain.getPlacecity());
            abPrisonersResult.setPlacecityName(prisonerMain.getPlacecityName());
            abPrisonersResult.setPlacecou(prisonerMain.getPlacecou());
            abPrisonersResult.setPlacevill(prisonerMain.getPlacevill());
            abPrisonersResult.setPlacecouName(prisonerMain.getPlacecouName());
            abPrisonersResult.setPlacevillName(prisonerMain.getPlacevillName());
            abPrisonersResult.setPlacenum(prisonerMain.getPlacenum());
            abPrisonersResult.setPriAddr(prisonerMain.getPriAddr());
            //用于司法所添加“迁移办理”，反显社矫中心、监狱、看守所录入人员的服刑单位
            abPrisonersResult.setPrison(prisonerMain.getPdanwei());
            abPrisonersResult.setPrisonname(prisonerMain.getPdanweiName());
            abPrisonersResult.setPdanwei(prisonerMain.getPdanwei());
            abPrisonersResult.setPdanweiname(prisonerMain.getPdanweiName());
            //创建时间
            abPrisonersResult.setCreateTime(date1);
            //创建账号
            abPrisonersResult.setCreateUser(userDTO.getAccount());
            //更新时间
            abPrisonersResult.setUpdateTime(date1);
            //更新账号
            abPrisonersResult.setUpdateUser(userDTO.getAccount());
            abPrisonersResult.setAzzt(Constants.NumberStr.NUM_STR_ONE);
            abPrisonersResult.setId(IdGen.strid());
            abPrisonersService.save(abPrisonersResult);
            AbXiaozuResultVo abXiaozuResultVo = new AbXiaozuResultVo();
            abXiaozuResultVo.setPriNum(prisonerMain.getPriNum());
            abXiaozuResultVo.setXname(prisonerMain.getPName());
            abXiaozuResultVo.setXsex(prisonerMain.getSex());
            if(null != prisonerMain.getAge()) {
                int age = DateUtil.getAge(prisonerMain.getAge());
                abXiaozuResultVo.setXnianling(String.valueOf(age));
            }
            //帮教对象自己
            abXiaozuResultVo.setXusertype(Constants.NumberStr.NUM_STR_ONE);
            abXiaozuResultVo.setParentId(abPrisonersResult.getId());
            //犯人表
            abXiaozuResultVo.setId(IdGen.strid());
            abXiaozuService.save(abXiaozuResultVo);
        }
        if(0 < i) {
            return Result.success(ReturnCode.SUCCESS);
        }
        return Result.failure(ReturnCode.SAVE_FAILED);
    }

    /**
     * 预安置管理 - 预释放人员衔接 - 未衔接 - 转入安置帮教
     * @param priNum 服刑人员编号
     * @return Result
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result moveToAnZhi(String priNum,UserDTO userDTO) {
        Date date1 = new Date();
        try {
            //修改主表衔接状态
            PrisonerMain prisonerMain = new PrisonerMain();
            prisonerMain.setUpdateUser(userDTO.getAccount());
            prisonerMain.setUpdateTime(date1);
            prisonerMain.setPriNum(priNum);
            prisonerMain.setFlag(Constants.NumberStr.NUM_STR_ONE);
            prisonerMainTowService.updateById(prisonerMain);
            //遍历基本表获取数据,并把数据存入安置表
            prisonerMain = prisonerMainMapper.selectPrisonerMain(priNum);
            AbPrisonersResultVo abPrisonersResultVo = saveblAbprisoners(prisonerMain);
            abPrisonersService.save(abPrisonersResultVo);
            AbXiaozuResultVo abXiaozuResultVo = saveXiaozu(prisonerMain);
            abXiaozuResultVo.setParentId(abPrisonersResultVo.getId());
            abXiaozuService.save(abXiaozuResultVo);
        } catch(Exception e) {
            log.error("转入安置帮教发生异常{}",e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.failure(ReturnCode.SAVE_FAILED);
        }
        return Result.success();
    }

    /**
     * 预安置管理 - 预释放人员衔接 - 衔接中 - 未衔接 - 列表
     * @param user 当前登录用户
     * @param searchmap 搜索条件
     * @param prisonerXjxxInVo 搜索条件,衔接信息
     * @return String
     */
    @Override
    public String getWxjList(UserDTO user,Map<String,Object> searchmap,PrisonerXjxxInVo prisonerXjxxInVo) {
        prisonerXjxxInVo.setPrison(user.getDepartid());
        prisonerXjxxInVo.setStateXj((String)searchmap.get("stateXj"));
        Page<Map<String,String>> page = new Page<>(Integer.parseInt(String.valueOf(searchmap.get("pageIndex"))) + 1,Integer.parseInt(String.valueOf(searchmap.get("pageSize"))));
        List<String> qitaKey;
        String qitaKeyStr = (String)searchmap.get("qitaKey");
        if(StringUtils.isNotBlank(qitaKeyStr)) {
            String[] split = qitaKeyStr.split(",");
            qitaKey = Arrays.asList(split);
            searchmap.put("qitaKey",qitaKey);
        }
        if(StringUtils.isNotBlank((String)searchmap.get("shenKey"))) {
            searchmap.put("shenKey",Sm4.encryptEcb((String)searchmap.get("shenKey")));
        }
        page.setSearchCount(false);
        long wxjListCount = prisonerMainMapper.getWxjListCount(prisonerXjxxInVo,user.getLevel(),searchmap);
        List<Map<String,String>> data = prisonerMainMapper.getWxjList(page,prisonerXjxxInVo,user.getLevel(),searchmap);
        //把监狱与和对应的省份匹配
        Map<Object,Object> mapProvince = stringRedisTemplate.opsForHash().entries("province");
        for(Map<String,String> item : data) {
            if(StringUtils.isEmpty(item.get("prisonName"))) {
                item.put("prisonName","");
            } else {
                item.put("prisonName",mapProvince.get(item.get("priNum")
                                                          .substring(0,2) + "0000") + "-" + item.get("prisonName"));
            }
        }
        page.setTotal(wxjListCount);
        page = page.setRecords(data);
        return PageReturnUtil.pageReturn(page);
    }

    /**
     * 预安置管理查看 - 基本信息 - 查询
     * @param priNum 服刑人员编号
     * @return Result
     */
    @Override
    public Result getBaseInfoViewByPriNum(String priNum) {
        Map<String,Object> map = prisonerMainMapper.getBaseInfoViewByPriNum(priNum);
        if(null != map && !map.isEmpty()) {
            return Result.success(map);
        }
        return Result.failure(ReturnCode.SELECT_FAILED);
    }

    /**
     * 预安置管理 - 预释放人员衔接 - 衔接失败 - 重新发起衔接 - 保存
     * @param departid 部门编号
     * @param departName 部门名称
     * @param account 登录账号
     * @param data 业务数据
     * @return Result
     */
    @Override
    public Result updateXjxx(String data,String departid,String departName,String account) {
        PrisonerXixxVo entity = JsonUtil.toBean(data,PrisonerXixxVo.class);
        boolean b = false;
        //修改主表衔接状态
        try {
            Date date1 = new Date();
            //衔接表
            PrisonerXjxx prisonerXjx = new PrisonerXjxx();
            prisonerXjx.setUpdateUser(account);
            prisonerXjx.setUpdateTime(date1);
            prisonerXjx.setTujing(entity.getTujing());
            prisonerXjx.setType(entity.getType());
            prisonerXjx.setYiban(entity.getYiban());
            prisonerXjx.setZhongdian(entity.getZhongdian());
            prisonerXjx.setLianxiren(entity.getLianxiren());
            prisonerXjx.setDianhua(entity.getDianhua());
            prisonerXjx.setJhsj(entity.getJhsj());
            prisonerXjx.setJhdd(entity.getJhdd());
            prisonerXjx.setSecondStateXj(Constants.NumberStr.NUM_STR_ZERO);
            UpdateWrapper<PrisonerXjxx> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("pri_num",entity.getPriNum());
            b = prisonerXjxxService.update(prisonerXjx,updateWrapper);
            PrisonerMain prisonerMain1 = prisonerMainMapper.selectPrisonerMain((entity.getPriNum()));
            String sfsId = prisonerMain1.getNativevill();
            String sfsName = prisonerMain1.getNativevillName();
            //衔接的同时生成一条回执中间表数据
            XjReceipt xjReceipt = new XjReceipt();
            xjReceipt.setXjid(IdGen.strid());
            xjReceipt.setPriNum(entity.getPriNum());
            xjReceipt.setSendCode(departid);
            xjReceipt.setSendName(departName);
            xjReceipt.setReceiveCode(sfsId);
            xjReceipt.setReceiveName(sfsName);
            xjReceipt.setSessionFlag(Constants.NumberStr.NUM_STR_ZERO);
            xjReceipt.setCreateUser(account);
            xjReceipt.setCreateTime(date1);
            xjReceipt.setUpdateUser(account);
            xjReceipt.setUpdateTime(date1);
            //flag=2表示衔接流程的回执标识
            xjReceipt.setFlag(Constants.NumberStr.NUM_STR_TWO);
            int i = xjReceiptMapper.saveXjReceive(xjReceipt);
            //保存信息表
            String xjid = xjReceipt.getXjid();
            XjReceiptData xjReceiptData = new XjReceiptData();
            xjReceiptData.setSessionId(xjid);
            xjReceiptData.setLiaisonMan(entity.getLianxiren());
            xjReceiptData.setLiaisonPhone(entity.getDianhua());
            xjReceiptData.setTakebackTime(entity.getJhsj());
            xjReceiptData.setTakebackAddress(entity.getJhdd());
            xjReceiptData.setOwnerFlag(Constants.NumberStr.NUM_STR_ONE);
            xjReceiptData.setCreateUser(account);
            xjReceiptData.setCreateTime(date1);
            xjReceiptData.setUpdateUser(account);
            xjReceiptData.setUpdateTime(date1);
            // 删除上传衔接证据（刑满释放通知书）
            uploadAppendixFileMapper.removeBatch(prisonerMain1.getId(),entity.getPriNum(),Constants.NumberStr.NUM_STR_TEN);
            int i1 = xjReceiptDataVoMapper.saveXjReceiveMessage(xjReceiptData);
            if(b && 0 < i && 0 < i1) {
                //同步衔接信息表、回执中间表、回执消息表到二次衔接省份
                String priNum = entity.getPriNum();
                //根据犯罪编号查询 跨省业务协调表
                PrisonerXjxx prisonerXjxx = prisonerXjxxService.getOne(updateWrapper);
                String secondProvince = prisonerXjxx.getSecondProvince();
                //二次衔接省份不是监狱省份同步衔接信息表、回执中间表、消息表 到第三省份
                String localCode = CodeUrlUtils.getLocalCode();
                if(!secondProvince.substring(0,2).equals(priNum.substring(0,2))) {
                    String prisonerXjxxDeleteSql = "delete from prisoner_xjxx where pri_num='" + priNum + "'";
                    String xjReceiptDeleteSql = "delete from xj_receipt where pri_num='" + priNum + "'";
                    String xjReceiptDataDeleteSql = "delete from xj_receipt_data where session_id in (select xjid from xj_receipt where prinum ='" + priNum + "')";
                    List<String> prisonerXjxxInsertSql = JdbcUtils.getInsertSql("prisoner_xjxx","pri_num",priNum,null,null,null,null);
                    List<String> xjReceiptInsertSql = JdbcUtils.getInsertSql("xj_receipt","prinum",priNum,null,null,null,null);
                    List<String> xjReceiptDataInsertSql = JdbcUtils.getInsertSql("xj_receipt_data","session_id",priNum,null,null,null,null);
                    String middleSql13 = JdbcUtils.createMiddleSql(priNum,prisonerXjxxDeleteSql,Constants.Number.NUM_ZERO,localCode,secondProvince);
                    middleJdbcTemplate.update(middleSql13);
                    String middleSql14 = JdbcUtils.createMiddleSql(priNum,xjReceiptDeleteSql,Constants.Number.NUM_ZERO,localCode,secondProvince);
                    middleJdbcTemplate.update(middleSql14);
                    String middleSql15 = JdbcUtils.createMiddleSql(priNum,xjReceiptDataDeleteSql,Constants.Number.NUM_ZERO,localCode,secondProvince);
                    middleJdbcTemplate.update(middleSql15);
                    for(String sql : prisonerXjxxInsertSql) {
                        String isql = JdbcUtils.createMiddleSql(priNum,sql,Constants.Number.NUM_ZERO,localCode,secondProvince);
                        middleJdbcTemplate.update(isql);
                    }
                    for(String sql : xjReceiptInsertSql) {
                        String isql = JdbcUtils.createMiddleSql(priNum,sql,Constants.Number.NUM_ZERO,localCode,secondProvince);
                        middleJdbcTemplate.update(isql);
                    }
                    for(String sql : xjReceiptDataInsertSql) {
                        String isql = JdbcUtils.createMiddleSql(priNum,sql,Constants.Number.NUM_ZERO,localCode,secondProvince);
                        middleJdbcTemplate.update(isql);
                    }
                }
            }
        } catch(DataAccessException e) {
            log.error("发生异常:",e);
        }
        if(b) {
            return Result.success();
        }
        return Result.failure(ReturnCode.FAILURE);
    }

    /**
     * 根据犯罪编号查询三五无三假等信息
     * @param priNum 服刑人员编号
     * @return Map<String,String>
     */
    @Override
    public Map<String,String> getSwSjInfo(String priNum) {
        return prisonerFxMapper.getSwSjInfo(priNum);
    }

    /**
     * 检查idnum是否存在
     * @param priNum 服刑人员编号
     * @param idnum 身份证
     * @return Result
     */
    @Override
    public Result checkIdNum(String priNum,String idnum) {
        if(Constants.NumberStr.NUM_STR_FU_ONE.equals(priNum)) {
            priNum = "";
        }
        if(!Constants.StrFinalValue.WU.equals(idnum)) {
            List<Integer> integer = prisonerMainMapper.existIdnum(Sm4.encryptEcb(idnum),priNum);
            if(null != integer && !integer.isEmpty()) {
                log.error(">>>>>>>>>>>>>>>>>>>>>>>>>身份证已存在<<<<<<<<<<<<<<<<<<<<<<<<<");
                return Result.failure(ReturnCode.FAILURE);
            }
        }
        return Result.success();
    }

    /**
     * 用于保存信息的状态
     * @param prisonerMain prisonerMain
     * @param i i
     * @return boolean
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean saveFlag(PrisonerMain prisonerMain,Integer i,UserDTO user) {
        boolean flag;
        // 1. 先更新中间状态表
        PrisaveTemp pt = new PrisaveTemp();
        PrisaveTemp prisaveTemp = prisaveTempMapper.selectById(prisonerMain.getPriNum());
        if(null == prisaveTemp) {
            String id = IdGen.strid();
            pt.setId(id);
        }
        pt.setPriNum(prisonerMain.getPriNum());
        if(i.equals(Constants.Number.NUM_ONE)) {
            pt.setMainFlag(Constants.Number.NUM_ONE);
        }
        if(i.equals(Constants.Number.NUM_TWO)) {
            pt.setFxFlag(Constants.Number.NUM_ONE);
        }
        if(i.equals(Constants.Number.NUM_THREE)) {
            pt.setZzFlag(Constants.Number.NUM_ONE);
        }
        if(i.equals(Constants.Number.NUM_FOUR)) {
            pt.setSrFlag(Constants.Number.NUM_ONE);
        }
        pt.setUpdateUser(user.getAccount());
        pt.setUpdateTime(new Date());
        flag = pt.insertOrUpdate();
        // 3. 更新状态
        PrisonerMain pm = prisonerMainMapper.selectPrisonerMain(prisonerMain.getPriNum());
        if(Constants.NumberStr.NUM_STR_ZERO.equals(pm.getState())) {
            flag = flag && updateState(prisonerMain.getPriNum());
        }
        return flag;
    }

    /**
     * 保存信息的时候，更新prisoner_mian的状态
     * @param prinum prinum
     * @return boolean
     */
    public boolean updateState(String prinum) {
        PrisaveTemp p = prisaveTempMapper.selectById(prinum);
        log.info("p:{}",p);
        int row = Constants.Number.NUM_FU_ONE;
        if(null != p) {
            int i = p.getMainFlag() + p.getFxFlag();
            if(Constants.Number.NUM_TWO == i) {
                row = prisonerMainMapper.updateStateByPrinum(prinum,Constants.NumberStr.NUM_STR_ONE);
            } else {
                row = Constants.Number.NUM_ZERO;
            }
        }
        return Constants.Number.NUM_FU_ONE != row;
    }

    /**
     * 查询idnum的罪犯信息
     * @param idNum 用户的号码
     * @return String
     */
    @Override
    public String findPrisonerByIdNum(String idNum) {
        //身份证是无不进行校验
        if(!Constants.StrFinalValue.WU.equals(idNum)) {
            PrisonerMain prisonerMain = prisonerMainMapper.selectOne(new QueryWrapper<PrisonerMain>().lambda()
                                                                                                     .eq(PrisonerMain::getIdNum,Sm4.encryptEcb(idNum))
                                                                                                     .ne(PrisonerMain::getDelFlag,Constants.NumberStr.NUM_STR_FU_ONE)
                                                                                                     .orderByDesc(PrisonerMain::getPriNum)
                                                                                                     .last("limit 1"));
            if(null == prisonerMain) {
                return null;
            } else {
                //判断这个人是否被删除，如果被删除，不做操作
                if(Constants.NumberStr.NUM_STR_FU_ONE.equals(prisonerMain.getDelFlag())) {
                    return null;
                } else {
                    //如果系统中有这个人，查看他的刑期止日和现刑期止日，看是否出狱，未出狱的不允许再次添加
                    Map<String,Object> priStopAndPriStopNow = prisonerFxMapper.getPriStopAndPriStopNow(prisonerMain.getPriNum());
                    if(priStopAndPriStopNow != null) {
                        Date date = new Date();
                        Date priStop = (Date)priStopAndPriStopNow.get("priStop");
                        Date priStopNow = (Date)priStopAndPriStopNow.get("priStopNow");
                        if(priStopNow != null) {
                            //当前日期小于现刑期止日，说明未出狱
                            if(date.compareTo(priStopNow) < Constants.Number.NUM_ZERO) {
                                return JsonUtil.toText(Result.failure(ReturnCode.FUXING_EXISTS));
                            }
                        } else if(priStop != null) {
                            //当前日期小于刑期止日，说明未出狱
                            if(Constants.Number.NUM_ZERO > date.compareTo(priStop)) {
                                return JsonUtil.toText(Result.failure(ReturnCode.FUXING_EXISTS));
                            }
                        }
                    }
                    prisonerMain.setId("");
                    prisonerMain.setPriNum("");
                    prisonerMain.setIdNum(Sm4.decryptEcb(prisonerMain.getIdNum()));
                    return JsonUtil.toText(prisonerMain);
                }
            }
        }
        return null;
    }

    /**
     * 根据犯罪编号查询罪犯信息
     * @param priNum 罪犯编号
     * @return PrisonerMain
     */
    @Override
    public PrisonerMain selectPmById(String priNum) {
        return prisonerMainMapper.selectOne(new QueryWrapper<PrisonerMain>().eq("pri_num",priNum));
    }

    /**
     * 推送数据展示，封装成PrisonerMainAndHcVo
     * @param id id
     * @return PrisonerMainAndHcVo
     */
    @Override
    public PrisonerMainAndHcVo getPrisonerMainAndHcVoById(String id) {
        PrisonerMainAndHcVo mainAndHcVo = verificationMapper.findHcById(id);
        String priNum = mainAndHcVo.getPriNum();
        PrisonerMain prisonerMain = prisonerMainMapper.selectOne(new QueryWrapper<PrisonerMain>().eq("pri_num",priNum)
                                                                                                 .last("limit 1"));
        if(null != prisonerMain) {
            //身份证号解密
            if(null != mainAndHcVo.getIdNum()) {
                mainAndHcVo.setIdNum(Sm4.decryptEcb(mainAndHcVo.getIdNum()));
            } else {
                mainAndHcVo.setIdNum("无");
            }
            //设置省编码
            if(null != prisonerMain.getNativepro()) {
                mainAndHcVo.setNativepro(prisonerMain.getNativepro());
            } else {
                mainAndHcVo.setNativepro("");
            }
            //设置省名称
            if(null != prisonerMain.getNativeproName()) {
                mainAndHcVo.setNativeproName(prisonerMain.getNativeproName());
            } else {
                mainAndHcVo.setNativeproName("");
            }
            //设置市编码
            if(null != prisonerMain.getNativecity()) {
                mainAndHcVo.setNativecity(prisonerMain.getNativecity());
            } else {
                mainAndHcVo.setNativecity("");
            }
            //设置市名称
            if(null != prisonerMain.getNativecityName()) {
                mainAndHcVo.setNativecityName(prisonerMain.getNativecityName());
            } else {
                mainAndHcVo.setNativeName("");
            }
            //设置区县编码
            if(null != prisonerMain.getNativecou()) {
                mainAndHcVo.setNativecou(prisonerMain.getNativecou());
            } else {
                mainAndHcVo.setNativecou("");
            }
            //设置区县名称
            if(null != prisonerMain.getNativecouName()) {
                mainAndHcVo.setNativecouName(prisonerMain.getNativecouName());
            } else {
                mainAndHcVo.setNativecouName("");
            }
            //设置乡镇编码
            if(null != prisonerMain.getNativevill()) {
                mainAndHcVo.setNativevill(prisonerMain.getNativevill());
            } else {
                mainAndHcVo.setNativevill("");
            }
            //设置乡镇名称
            if(null != prisonerMain.getNativecouName()) {
                mainAndHcVo.setNativevillName(prisonerMain.getNativevillName());
            } else {
                mainAndHcVo.setNativeName("");
            }
            //设置详细地址
            if(null != prisonerMain.getNativenum()) {
                mainAndHcVo.setNativenum(prisonerMain.getNativenum());
            } else {
                mainAndHcVo.setNativenum("");
            }
        }
        //获取罪名编号
        String critype = mainAndHcVo.getCritype();
        //封装一下罪名
        if(!StringUtils.isEmpty(critype)) {
            List<Map<String,String>> codeNameList = systemCodeMapper.getCodeNameByCodeId(Arrays.asList(critype.split(",")));
            List<String> nameList = new ArrayList<>(16);
            codeNameList.forEach(map -> nameList.add(String.valueOf(map.get("codeName"))));
            mainAndHcVo.setCritypeName(StringUtils.join(nameList,','));
        }
        return mainAndHcVo;
    }

    /**
     * 根据id获取名称
     * @param id id
     * @return SystemCode
     */
    private SystemCode getAdminCodeById(String id) {
        return systemCodeMapper.selectOne(new QueryWrapper<SystemCode>().eq("code_id",id).eq("code_type","2_1")
                                                                        .last("limit 1"));
    }

    /**
     * 湖南个性化 - 衔接回执
     * @param userDTO 部门名称
     * @param prisonerXjxx 罪犯衔接信息
     */
    public void xjhz(UserDTO userDTO,PrisonerXixxVo prisonerXjxx) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Map<String,String> hz = new HashMap<>(16);
        //根据罪犯编号去查询湖南个性化对接存储记录表
        HnInterfaceOpposite hnInterfaceOpposite = hnInterfaceOppositeMapper.selectHnInterfaceOppositeByPriNum(prisonerXjxx.getPriNum(),Constants.HnInterfaceDocking.ZERO_SEVEN_ZERO_TWO_A);
        hnInterfaceOpposite.setHzXjZip(Constants.NumberStr.NUM_STR_ONE);
        if(hnInterfaceOpposite.insertOrUpdate()) {
            HnMessageVo hnMessage = JsonUtil.toBean(hnInterfaceOpposite.getMessageData(),HnMessageVo.class);
            hz.put("KBMBAH",hnMessage.getKbmbah());
            hz.put("LCSLBH",hnMessage.getLcslbh());
            hz.put("XJJG_CODE",Constants.NumberStr.NUM_STR_THREE.equals(prisonerXjxx.getStatexj()) ? Constants.NumberStr.NUM_STR_TWO : Constants.NumberStr.NUM_STR_ONE);
            hz.put("XJJG_NAME",Constants.NumberStr.NUM_STR_THREE.equals(prisonerXjxx.getStatexj()) ? Constants.HnInterfaceDocking.FAILURE : Constants.HnInterfaceDocking.SUCCESS);
            hz.put("SSDR",userDTO.getDepartName());
            hz.put("JS_TIME",sdf.format(new Date()));
            hz.put("BZ",prisonerXjxx.getRemark());
            hz.put("PROCESS_NO",Constants.HnInterfaceDocking.ZERO_SEVEN_ZERO_TWO_F);
            hz.put("AJMC",hnMessage.getAjmc());
            hz.put("LCLX_CODE",Constants.HnInterfaceDocking.ZERO_SEVEN_ZERO_TWO_F);
            hz.put("LCLX_NAME","完成衔接");
            hz.put("JSDWLX","4B");
            Map<String,Map<String,String>> tsmessage = provinceCodes3Config.getTSMESSAGE();
            Map<String,String> fsdwCodes = tsmessage.get("FSDW_CODE");
            for(Map.Entry<String,String> fsdw : fsdwCodes.entrySet()) {
                if(fsdw.getValue().contains(hnMessage.getFsdwCode())) {
                    hz.put("JSDW_CODE",fsdw.getKey());
                }
            }
            hz.put("JSDW_NAME",hnMessage.getFsdwName());
            hz.put("JSDWSZD",hnMessage.getFsdwszd());
            hz.put("JSDWXZQ_CODE",hnMessage.getJsdwxzqCode());
            hz.put("JSDWXZQ_NAME",hnMessage.getJsdwxzqName());
            hz.put("FSDWLX","5D");
            hz.put("FSDW_CODE",hnMessage.getJsdwCode());
            hz.put("FSDW_NAME",hnMessage.getJsdwName());
            hz.put("FSDWSZD",hnMessage.getJsdwszd());
            hz.put("FSDWXZQ_CODE",hnMessage.getFsdwxzqCode());
            hz.put("FSDWXZQ_NAME",hnMessage.getFsdwxzqName());
            hz.put("FS_TIME",sdf.format(new Date()));
            hz.put("YSR",userDTO.getDepartName());
            hz.put("YSRDH",userDTO.getTelphone());
            hz.put("CBR",userDTO.getDepartName());
            hz.put("CBRDH",hnMessage.getCbrdh());
            hz.put("ZIPNAME",userDTO.getTelphone());
            xmlMinitoringService.processOut(hz);
        }
    }

    /**
     * 根据身份证、姓名查询数据库中数据的服刑信息
     * @param idNum 身份证
     * @param pName 姓名
     * @return String -1：正常 0：服刑人员已存在，未出狱 1：基本信息已存在
     */
    private String checkIdNumRepeat(String idNum,String pName) {
        Date date = new Date();
        PrisonerMain newPrisonerMain = prisonerMainMapper.verifyIdNumer(Sm4.encryptEcb(idNum),pName);
        if(null != newPrisonerMain) {
            PrisonerFx prisonerFx = prisonerFxMapper.selectOne(new QueryWrapper<PrisonerFx>().lambda()
                                                                                             .eq(PrisonerFx::getPriNum,newPrisonerMain.getPriNum())
                                                                                             .last("limit 1"));
            if(null != prisonerFx) {
                String pritime = prisonerFx.getPritime();
                boolean case1 = StrUtil.contains(pritime,Constants.PritimeTypeNow.PRITIME_WUQI,Constants.PritimeTypeNow.PRITIME_SIHUAN,Constants.PritimeTypeNow.PRITIME_SIXING);
                boolean case2 = null != prisonerFx.getPriStopNow() && prisonerFx.getPriStopNow()
                                                                                .getTime() > date.getTime();
                boolean case3 = null != prisonerFx.getPriStop() && prisonerFx.getPriStop().getTime() > date.getTime();
                if(case1 || case2 || case3) {
                    return Constants.NumberStr.NUM_STR_ZERO;
                }
            } else {
                return Constants.NumberStr.NUM_STR_ONE;
            }
        }
        return Constants.NumberStr.NUM_STR_FU_ONE;
    }

    /**
     * 山西个性化需求: 检查是否更改基本信息
     * @param prisonerMain prisonerMain
     * @param userDTO userDTO
     */
    private void changePrisonerMain(PrisonerMain prisonerMain,UserDTO userDTO) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
        //查询出当前库中的对象信息
        PrisonerMain prisonerMain1 = prisonerMainMapper.selectPrisonerMain(prisonerMain.getPriNum());
        //比较前端传的参数对象和数据库对象是否一致prisonerMain、prisonerInfoByPrinm
        String[] ignoreFields = {"id","priNum","sex","nationality","idNum","idType","age","education","prisonFather","pdanwei","pdanweiName","addtime","priAddr","hj_type","detail_type","pstate","ptype","state","stateXj","flag","delFlag","adduserid","addusername","optime","useridXj","usernameXj","createUser","createTime","updateUser","updateTime"};
        Map<String,List<Object>> stringListMap = CheckFieldValue.compareFields(prisonerMain,prisonerMain1,ignoreFields);
        assert stringListMap != null;
        for(String s : stringListMap.keySet()) {
            String key;
            List<Object> value;
            key = s;
            value = stringListMap.get(key);
            List<ChangeTable> changeTables = changeTableMapper.searchChangePriNum(prisonerMain.getPriNum(),"prisoner_main",key);
            if(0 < changeTables.size()) {
                if(value.get(1) instanceof Date) {
                    // 时间单独处理
                    changeTableMapper.updateChangeValue(prisonerMain.getPriNum(),"prisoner_main",key,format.format(value.get(1)),changeTables.get(0)
                                                                                                                                             .getChangeValue() + "," + userDTO.getAccount() + ":" + value.get(0),changeTables.get(0)
                                                                                                                                                                                                                             .getId());
                    continue;
                }
                changeTableMapper.updateChangeValue(prisonerMain.getPriNum(),"prisoner_main",key,(String)value.get(1),changeTables.get(0)
                                                                                                                                  .getChangeValue() + "," + userDTO.getAccount() + ":" + value.get(0),changeTables.get(0)
                                                                                                                                                                                                                  .getId());
                //追加
            } else {
                if(value.get(1) instanceof Date) {
                    // 时间单独处理
                    changeTableMapper.saveChange(prisonerMain.getPriNum(),"prisoner_main",key,format.format(value.get(1)),userDTO.getAccount() + ":" + format.format(value.get(0)));
                    continue;
                }
                //新增
                changeTableMapper.saveChange(prisonerMain.getPriNum(),"prisoner_main",key,(String)value.get(1),userDTO.getAccount() + ":" + value.get(0));
            }
        }
    }

    /**
     * 山西个性化需求:预安置人员管理 - 全部人员管理
     * @param pageIndex pageIndex
     * @param pageSize pageSize
     * @param querykey querykey
     * @param idNum idNum
     * @return String
     */
    @Override
    public String getQbryList(Integer pageIndex,Integer pageSize,String querykey,String idNum,String sortField,String sortOrder) {
        Map<String,Object> mapTem = JsonUtil.toMap(querykey);
        for(Map.Entry<String,Object> entry : mapTem.entrySet()) {
            if(StringUtils.equals(entry.getValue().toString(),Constants.NumberStr.NUM_STR_FU_ONE)) {
                mapTem.put(entry.getKey(),null);
            }
        }
        if(!StringUtils.isEmpty(idNum) && !StringUtils.equals(idNum,Constants.NumberStr.NUM_STR_FU_ONE)) {
            idNum = Sm4.encryptEcb(idNum);
        }
        if(StringUtils.equals(idNum,Constants.NumberStr.NUM_STR_FU_ONE)) {
            idNum = null;
        }
        mapTem.put("idNum",idNum);
        Page<Map<String,String>> page = new Page<>(pageIndex + 1,pageSize);
        page.setOptimizeCountSql(false);
        page.setSearchCount(false);
        page.setTotal(prisonerMainMapper.getQbryListCount(mapTem));
        page = page.setRecords(prisonerMainMapper.getQbryList(page,mapTem,sortField,sortOrder));
        return PageReturnUtil.pageReturn(page);
    }

    /**
     * 补录安帮信息
     * @param prisonerMain prisonerMain
     * @return AbPrisonersResultVo
     */
    private AbPrisonersResultVo saveblAbprisoners(PrisonerMain prisonerMain) {
        Date date = new Date();
        AbPrisonersResultVo abPrisonersResultVo = new AbPrisonersResultVo();
        abPrisonersResultVo.setId(IdGen.strid());
        abPrisonersResultVo.setPriNum(prisonerMain.getPriNum());
        abPrisonersResultVo.setPname(prisonerMain.getPName());
        abPrisonersResultVo.setUsedname(prisonerMain.getUsedName());
        abPrisonersResultVo.setSex(prisonerMain.getSex());
        abPrisonersResultVo.setNationality(prisonerMain.getNationality());
        abPrisonersResultVo.setIdnum(prisonerMain.getIdNum());
        abPrisonersResultVo.setAge(prisonerMain.getAge());
        abPrisonersResultVo.setEducation(prisonerMain.getEducation());
        abPrisonersResultVo.setState(prisonerMain.getState());
        abPrisonersResultVo.setAdduserid(prisonerMain.getAdduserid());
        abPrisonersResultVo.setAddusername(prisonerMain.getAddusername());
        abPrisonersResultVo.setPstate(prisonerMain.getPstate());
        abPrisonersResultVo.setPtype(prisonerMain.getPtype());
        abPrisonersResultVo.setPdanwei(prisonerMain.getPdanwei());
        abPrisonersResultVo.setPdanweiname(prisonerMain.getPdanweiName());
        abPrisonersResultVo.setAddtime(date);
        abPrisonersResultVo.setPriAddr(prisonerMain.getPriAddr());
        abPrisonersResultVo.setNativepro(prisonerMain.getNativepro());
        abPrisonersResultVo.setNativecity(prisonerMain.getNativecity());
        abPrisonersResultVo.setNativevill(prisonerMain.getNativevill());
        abPrisonersResultVo.setNativecou(prisonerMain.getNativecou());
        abPrisonersResultVo.setNativeproName(prisonerMain.getNativeproName());
        abPrisonersResultVo.setNativecityName(prisonerMain.getNativecityName());
        abPrisonersResultVo.setNativecouName(prisonerMain.getNativecouName());
        abPrisonersResultVo.setNativevillName(prisonerMain.getNativevillName());
        abPrisonersResultVo.setNativenum(prisonerMain.getNativenum());
        //设置居住地址编码
        abPrisonersResultVo.setPlacepro(prisonerMain.getPlacepro());
        abPrisonersResultVo.setPlacecity(prisonerMain.getPlacecity());
        abPrisonersResultVo.setPlacecou(prisonerMain.getPlacecou());
        abPrisonersResultVo.setPlacevill(prisonerMain.getPlacevill());
        //设置居住地址
        abPrisonersResultVo.setPlaceproName(prisonerMain.getPlaceproName());
        abPrisonersResultVo.setPlacecityName(prisonerMain.getPlacecityName());
        abPrisonersResultVo.setPlacecouName(prisonerMain.getPlacecouName());
        abPrisonersResultVo.setPlacevillName(prisonerMain.getPlacevillName());
        abPrisonersResultVo.setPlacenum(prisonerMain.getPlacenum());
        //表示已经安帮
        abPrisonersResultVo.setCreateTime(date);
        abPrisonersResultVo.setCreateUser(prisonerMain.getCreateUser());
        abPrisonersResultVo.setUpdateTime(date);
        abPrisonersResultVo.setUpdateUser(prisonerMain.getCreateUser());
        abPrisonersResultVo.setAge(prisonerMain.getAge());
        // 补录信息默认核查成功与衔接成功
        abPrisonersResultVo.setStateXj(Constants.NumberStr.NUM_STR_ONE);
        abPrisonersResultVo.setFlag(Constants.NumberStr.NUM_STR_ONE);
        abPrisonersResultVo.setAzzt(Constants.NumberStr.NUM_STR_ONE);
        return abPrisonersResultVo;
    }

    /**
     * 补录衔接信息
     * @param prisonerMain prisonerMain
     * @param paramMap paramMap
     */
    private void saveblPrisonerXjxx(PrisonerMain prisonerMain,Map<String,Object> paramMap) {
        PrisonerXjxx prisonerXjxx = new PrisonerXjxx();
        prisonerXjxx.setId(IdGen.strid());
        prisonerXjxx.setPriNum(prisonerMain.getPriNum());
        prisonerXjxx.setAdduserid(prisonerMain.getAdduserid());
        prisonerXjxx.setAddusername(prisonerMain.getAddusername());
        Date date = new Date();
        prisonerXjxx.setCreateUser(prisonerMain.getCreateUser());
        prisonerXjxx.setCreateTime(date);
        prisonerXjxx.setUpdateUser(prisonerMain.getCreateUser());
        prisonerXjxx.setUpdateTime(date);
        prisonerXjxx.setTujing(paramMap.get("tujing").toString());
        prisonerXjxxMapper.insertBlXjxx(prisonerXjxx);
    }

    /**
     * 保存小组信息
     * @param prisonerMain prisonerMain
     */
    private AbXiaozuResultVo saveXiaozu(PrisonerMain prisonerMain) {
        Date date = new Date();
        AbXiaozuResultVo abXiaozuResultVo = new AbXiaozuResultVo();
        abXiaozuResultVo.setPriNum(prisonerMain.getPriNum());
        abXiaozuResultVo.setXname(prisonerMain.getPName());
        abXiaozuResultVo.setXsex(prisonerMain.getSex());
        if(null != prisonerMain.getAge()) {
            int age = DateUtil.getAge(prisonerMain.getAge());
            abXiaozuResultVo.setXnianling(String.valueOf(age));
        }
        //帮教对象自己
        abXiaozuResultVo.setXusertype(Constants.NumberStr.NUM_STR_ONE);
        //犯人表
        abXiaozuResultVo.setId(IdGen.strid());
        abXiaozuResultVo.setCreateTime(date);
        abXiaozuResultVo.setCreateUser(prisonerMain.getAddusername());
        abXiaozuResultVo.setUpdateTime(date);
        abXiaozuResultVo.setUpdateUser(prisonerMain.getAddusername());
        return abXiaozuResultVo;
    }
}